ksmux

package module
v0.0.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2024 License: BSD-3-Clause Imports: 41 Imported by: 3

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	MEDIA_DIR                = "media"
	HOST                     = ""
	PORT                     = ""
	ADDRESS                  = ""
	DOMAIN                   = ""
	IsTLS                    = false
	SUBDOMAINS               = []string{}
	ReadTimeout              = 5 * time.Second
	WriteTimeout             = 20 * time.Second
	IdleTimeout              = 20 * time.Second
	FuncBeforeServerShutdown = func(srv *http.Server) error {
		return nil
	}
	// context
	MultipartSize = 10 << 20

	// docs
	DocsOutJson           = "."
	DocsEntryFile         = "ksmuxdocs/ksmuxdocs.go"
	OnDocsGenerationReady = func() {}

	// ctx cookies
	COOKIES_Expires  = 24 * 7 * time.Hour
	COOKIES_SameSite = http.SameSiteStrictMode
	COOKIES_HttpOnly = true
	COOKIES_SECURE   = true
)
View Source
var Cors = func(allowed ...string) func(http.Handler) http.Handler {
	corsEnabled = true
	if len(allowed) == 0 {
		allowed = append(allowed, "*")
	}
	for i := range allowed {
		if allowed[i] == "*" {
			continue
		}
		allowed[i] = strings.ReplaceAll(allowed[i], "localhost", "127.0.0.1")
		if !strings.HasPrefix(allowed[i], "http") {
			allowed[i] = "http://" + allowed[i]
		}
	}
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if allowed[0] == "*" {
				w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
			} else {
				w.Header().Set("Access-Control-Allow-Origin", allowed[0])
			}
			w.Header().Set("Access-Control-Allow-Methods", "*")
			w.Header().Set("Access-Control-Allow-Credentials", "true")
			w.Header().Set("Access-Control-Allow-Headers", "*")
			if r.Method == "OPTIONS" {
				w.Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, X-Korm, Authorization, Token, X-Token")
				w.WriteHeader(http.StatusNoContent)
				return
			}

			h.ServeHTTP(w, r)
		})
	}
}
View Source
var DocsGeneralDefaults = DocsGeneralInfo{
	Title:          "Korm Api Documentation",
	Version:        "1.0.0",
	Host:           "localhost:9313",
	BasePath:       "/",
	Description:    "Swagger Api Documentation for Korm",
	TermsOfService: "http://swagger.io/terms/",
	ContactName:    "API Support",
	ContactUrl:     "https://kamalshkeir.dev",
	ContactEmail:   "support@email.com",
	LicenseName:    "Apache 2.0",
	LicenseUrl:     "http://www.apache.org/licenses/LICENSE-2.0.html",
}
View Source
var MatchedRoutePathParam = "$ksmuxdone"

MatchedRoutePathParam is the Param name under which the path of the matched route is stored, if Router.SaveMatchedPath is set.

Functions

func BeforeRenderHtml

func BeforeRenderHtml(uniqueName string, fn func(reqCtx context.Context, data *map[string]any))

BeforeRenderHtml executed before every html render, you can use reqCtx.Value(key).(type.User) for example and add data to templates globaly

func CheckAndInstallSwagger

func CheckAndInstallSwagger() error

func ExecuteRawHtml

func ExecuteRawHtml(rawTemplateName string, data map[string]any) (string, error)

func GenerateGoDocsComments

func GenerateGoDocsComments(pkgName ...string)

func GenerateJsonDocs

func GenerateJsonDocs(entryDocsFile ...string)

func GenerateUUID

func GenerateUUID() (string, error)

func GetPrivateIp

func GetPrivateIp() string

func Graceful

func Graceful(f func() error) error

func Gzip

func Gzip() func(http.Handler) http.Handler

func IgnoreLogsEndpoints added in v0.0.5

func IgnoreLogsEndpoints(pathContain ...string)

func Limiter added in v0.0.7

func Limiter(conf *ConfigLimiter) func(http.Handler) http.Handler

func Logs

func Logs(callback ...func(method, path, remote string, status int, took time.Duration)) func(http.Handler) http.Handler

func NewFuncMap added in v0.0.6

func NewFuncMap(funcMap map[string]any)

func SaveMultipartFile

func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error)

SaveMultipartFile Save MultipartFile

func SaveRawHtml

func SaveRawHtml(templateRaw string, templateName string)

SaveRawHtml save templateRaw as templateName to be able to use it like c.RawHtml

func SliceContains

func SliceContains[T comparable](elems []T, vs ...T) bool

func StringContains

func StringContains(s string, subs ...string) bool

func ToSlug

func ToSlug(s string) (string, error)

func UpgradeConnection

func UpgradeConnection(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*ws.Conn, error)

Types

type ConfigLimiter added in v0.0.7

type ConfigLimiter struct {
	Message       string        // default "TOO MANY REQUESTS"
	RateEvery     time.Duration // default 10 min
	BurstsN       int           // default 100
	CheckEvery    time.Duration // default 5 min
	BlockDuration time.Duration // default 10 min
}

type Context

type Context struct {
	http.ResponseWriter
	*http.Request
	Params Params
	// contains filtered or unexported fields
}

func (*Context) AddHeader

func (c *Context) AddHeader(key, value string)

AddHeader Add append a header value to key if exist

func (*Context) AddSSEHeaders added in v0.0.4

func (c *Context) AddSSEHeaders()

func (*Context) BindBody

func (c *Context) BindBody(strctPointer any, isXML ...bool) error

scan body to struct, default json

func (*Context) BodyJson

func (c *Context) BodyJson() map[string]any

BodyJson get json body from request and return map USAGE : data := c.BodyJson(r)

func (*Context) BodyText

func (c *Context) BodyText() string

func (*Context) Context

func (c *Context) Context() context.Context

Context return request context

func (*Context) DeleteCookie

func (c *Context) DeleteCookie(key string)

DeleteCookie delete cookie with specific key

func (*Context) DeleteFile

func (c *Context) DeleteFile(path string) error

DELETE FILE

func (*Context) Download

func (c *Context) Download(data_bytes []byte, asFilename string)

Download download data_bytes(content) asFilename(test.json,data.csv,...) to the client

func (*Context) Error

func (c *Context) Error(code int, message string)

Error send json error

func (*Context) Flush

func (c *Context) Flush() bool

func (*Context) GetCookie

func (c *Context) GetCookie(key string) (string, error)

GetCookie get cookie with specific key

func (*Context) GetKey

func (c *Context) GetKey(key string) (any, bool)

GetKey return request context value for given key

func (*Context) GetUserIP

func (c *Context) GetUserIP() string

func (*Context) Html

func (c *Context) Html(template_name string, data map[string]any)

Html return template_name with data to the client

func (*Context) IsAuthenticated

func (c *Context) IsAuthenticated(key ...string) bool

func (*Context) Json

func (c *Context) Json(data any)

Json return json to the client

func (*Context) JsonIndent

func (c *Context) JsonIndent(data any)

JsonIndent return json indented to the client

func (*Context) MatchedPath

func (c *Context) MatchedPath() string

func (*Context) NamedRawHtml

func (c *Context) NamedRawHtml(rawTemplateName string, data map[string]any) error

NamedRawHtml render rawTemplateName with data using go engine, make sure to save the html using ksmux.SaveRawHtml outside the handler

func (*Context) Param

func (c *Context) Param(name string) string

func (*Context) ParseMultipartForm

func (c *Context) ParseMultipartForm(size ...int64) (formData url.Values, formFiles map[string][]*multipart.FileHeader)

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam get query param

func (*Context) RawHtml

func (c *Context) RawHtml(rawTemplate string, data map[string]any) error

NamedRawHtml render rawTemplateName with data using go engine, make sure to save the html using ksmux.SaveRawHtml outside the handler

func (*Context) Redirect

func (c *Context) Redirect(path string)

Redirect redirect the client to the specified path with a custom code, default status 307

func (*Context) SaveFile

func (c *Context) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile save file to path

func (*Context) ServeEmbededFile

func (c *Context) ServeEmbededFile(content_type string, embed_file []byte)

ServeEmbededFile serve an embeded file from handler

func (*Context) ServeFile

func (c *Context) ServeFile(content_type, path_to_file string)

ServeFile serve a file from handler

func (*Context) SetCookie

func (c *Context) SetCookie(key, value string, maxAge ...time.Duration)

SetCookie set cookie given key and value

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader Set the header value to the new value, old removed

func (*Context) SetKey

func (c *Context) SetKey(key string, value any)

func (*Context) SetStatus

func (c *Context) SetStatus(statusCode int)

SetHeader Set the header value to the new value, old removed

func (*Context) SliceParams

func (c *Context) SliceParams() Params

func (*Context) Status

func (c *Context) Status(code int) *Context

Status set status to context, will not be writed to header

func (*Context) Stream

func (c *Context) Stream(response string) error

Stream send SSE Streaming Response

func (*Context) Text

func (c *Context) Text(body string)

Text return text with custom code to the client

func (*Context) UpgradeConnection added in v0.0.4

func (c *Context) UpgradeConnection() (*ws.Conn, error)

func (*Context) UploadFile

func (c *Context) UploadFile(received_filename, folder_out string, acceptedFormats ...string) (string, []byte, error)

UploadFile upload received_filename into folder_out and return url,fileByte,error

func (*Context) UploadFiles

func (c *Context) UploadFiles(received_filenames []string, folder_out string, acceptedFormats ...string) ([]string, [][]byte, error)

func (*Context) User

func (c *Context) User(key ...string) (any, bool)

User is alias of c.Keys but have key default to 'user'

type ContextKey

type ContextKey string

type DocsGeneralInfo

type DocsGeneralInfo struct {
	Title          string
	Version        string
	Host           string
	BasePath       string
	Description    string
	TermsOfService string
	ContactName    string
	ContactUrl     string
	ContactEmail   string
	LicenseName    string
	LicenseUrl     string
}

type DocsIn

type DocsIn struct {
	Name        string
	In          string
	Type        string
	Required    bool
	Description string
}

func (DocsIn) String

func (dp DocsIn) String() string

type DocsOut

type DocsOut struct {
	StatusCode        string
	TypeObjectOrArray string
	TypePath          string
	Value             string
	Extra             string
}

func (DocsOut) String

func (dr DocsOut) String() string

type DocsRoute

type DocsRoute struct {
	Method           string
	Summary          string
	Description      string
	Tags             string
	Accept           string
	Produce          string
	Response         string
	FailureResponses []string
	Params           []string
	Pattern          string
	Triggered        bool
}

type GroupRouter

type GroupRouter struct {
	*Router
	Group string
	// contains filtered or unexported fields
}

func (*GroupRouter) Delete

func (gr *GroupRouter) Delete(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Get

func (gr *GroupRouter) Get(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Head

func (gr *GroupRouter) Head(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Options

func (gr *GroupRouter) Options(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Patch

func (gr *GroupRouter) Patch(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Post

func (gr *GroupRouter) Post(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Put

func (gr *GroupRouter) Put(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Use

func (gr *GroupRouter) Use(middlewares ...func(Handler) Handler)

Use chain handler middlewares

type Handler

type Handler func(c *Context)

Handler is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (path variables).

func BasicAuth

func BasicAuth(ksmuxHandlerFunc Handler, user, pass string) Handler

func (Handler) ServeHTTP

func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func GetParamsFromCtx

func GetParamsFromCtx(ctx context.Context) Params

GetParamsFromCtx get params from ctx for http.Handler

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type Route

type Route struct {
	Method   string
	Pattern  string
	Origines string
	Handler  Handler
	Docs     *DocsRoute
}

func (*Route) Accept

func (r *Route) Accept(accept string) *Route

Accept set docs accept, default 'json'

func (*Route) Description

func (r *Route) Description(description string) *Route

func (*Route) In

func (r *Route) In(docsParam ...string) *Route

In must be like "name in typePath required 'desc'" or you can use ksmux.DocsIn.String() method

func (*Route) Out

func (r *Route) Out(sucessResponse string, failureResponses ...string) *Route

Out must be like "200 {object}/{array}/{string} app1.Account/string 'okifstring'" or you can use ksmux.DocsOut.String() method

func (*Route) Produce

func (r *Route) Produce(produce string) *Route

Produce set docs produce, default 'json'

func (*Route) Summary

func (r *Route) Summary(summary string) *Route

func (*Route) Tags

func (r *Route) Tags(tags ...string) *Route

type Router

type Router struct {
	Server *http.Server

	// If enabled, adds the matched route path onto the http.Request context
	// before invoking the handler.
	// The matched route path is only added to handlers of routes that were
	// registered when this option was enabled.
	SaveMatchedPath bool

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 308 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handlre is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handler can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 308 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// An optional http.Handler that is called on automatic OPTIONS requests.
	// The handler is only called if HandleOPTIONS is true and no OPTIONS
	// handler for the specific path was set.
	// The "Allowed" header is set before calling the handler.
	GlobalOPTIONS http.Handler

	// Configurable http.Handler which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFound http.Handler

	// Configurable http.Handler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed http.Handler

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	PanicHandler func(http.ResponseWriter, *http.Request, interface{})
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func New

func New() *Router

New returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) Delete

func (r *Router) Delete(path string, handler Handler, origines ...string) *Route

Delete is a shortcut for router.Handle(http.MethodDelete, path, handler)

func (*Router) EmbededStatics

func (router *Router) EmbededStatics(embeded embed.FS, pathLocalDir, webPath string, handlerMiddlewares ...func(handler Handler) Handler)

func (*Router) EmbededTemplates

func (router *Router) EmbededTemplates(template_embed embed.FS, rootDir string) error

func (*Router) EnableDomainCheck added in v0.0.3

func (router *Router) EnableDomainCheck()

EnableDomainCheck enable only the domain check from ksmux methods Get,Post,... (does not add cors middleware)

func (*Router) Get

func (r *Router) Get(path string, handler Handler, origines ...string) *Route

Get is a shortcut for router.Handle(http.MethodGet, path, handler)

func (*Router) Group

func (router *Router) Group(prefix string) *GroupRouter

Group create group path

func (*Router) Handle

func (r *Router) Handle(method, path string, handler Handler, origines ...string) *Route

Handle registers a new request handler with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc, origines ...string) *Route

HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handler.

func (*Router) Head

func (r *Router) Head(path string, handler Handler, origines ...string) *Route

Head is a shortcut for router.Handle(http.MethodHead, path, handler)

func (*Router) LocalStatics

func (router *Router) LocalStatics(dirPath, webPath string, handlerMiddlewares ...func(handler Handler) Handler)

func (*Router) LocalTemplates

func (router *Router) LocalTemplates(pathToDir string) error

func (*Router) Lookup

func (r *Router) Lookup(method, path string) (Handler, Params, bool, string)

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handler function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) NewFuncMap

func (router *Router) NewFuncMap(funcMap map[string]any)

func (*Router) NewTemplateFunc

func (router *Router) NewTemplateFunc(funcName string, function any)

func (*Router) Options

func (r *Router) Options(path string, handler Handler, origines ...string) *Route

Options is a shortcut for router.Handle(http.MethodOptions, path, handler)

func (*Router) Patch

func (r *Router) Patch(path string, handler Handler, origines ...string) *Route

Patch is a shortcut for router.Handle(http.MethodPatch, path, handler)

func (*Router) Post

func (r *Router) Post(path string, handler Handler, origines ...string) *Route

Post is a shortcut for router.Handle(http.MethodPost, path, handler)

func (*Router) Put

func (r *Router) Put(path string, handler Handler, origines ...string) *Route

Put is a shortcut for router.Handle(http.MethodPut, path, handler)

func (*Router) ReverseProxy

func (router *Router) ReverseProxy(host, toURL string) (newRouter *Router)

func (*Router) Run

func (router *Router) Run(addr string)

Run HTTP server on address

func (*Router) RunAutoTLS

func (router *Router) RunAutoTLS(domainName string, subdomains ...string)

RunAutoTLS HTTPS server generate certificates and handle renew

func (*Router) RunTLS

func (router *Router) RunTLS(addr, cert, certKey string)

RunTLS HTTPS server using certificates

func (*Router) ServeEmbededFile

func (router *Router) ServeEmbededFile(file []byte, endpoint, contentType string)

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, root http.FileSystem)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:

router.ServeFiles("/src/*filepath", http.Dir("/var/www"))

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

func (*Router) ServeLocalFile

func (router *Router) ServeLocalFile(file, endpoint, contentType string)

func (*Router) Use

func (router *Router) Use(midws ...func(http.Handler) http.Handler)

Use chain global router middlewares

func (*Router) WithDocs

func (router *Router) WithDocs(genJsonDocs bool, genGoDocs ...bool) *Router

WithDocs check and install swagger, and generate json and go docs at the end , after the server run, you can use ksmux.OnDocsGenerationReady() genGoDocs default to true if genJsonDocs

func (*Router) WithMetrics

func (router *Router) WithMetrics(httpHandler http.Handler, path ...string)

WithMetrics take prometheus handler and serve metrics on path or default /metrics

func (*Router) WithPprof

func (router *Router) WithPprof(path ...string)

WithPprof enable std library pprof at /debug/pprof, prefix default to 'debug'

type StatusRecorder

type StatusRecorder struct {
	http.ResponseWriter
	Status int
}

func (*StatusRecorder) Flush

func (r *StatusRecorder) Flush()

func (*StatusRecorder) Hijack

func (r *StatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)

func (*StatusRecorder) WriteHeader

func (r *StatusRecorder) WriteHeader(status int)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL