Documentation ¶
Index ¶
- Variables
- func BeforeRenderHtml(uniqueName string, fn func(c *Context, data *map[string]any))
- func CheckAndInstallSwagger() error
- func CopyFile(src, dst string, BUFFERSIZE int64) error
- func ExecuteRawHtml(rawTemplateName string, data map[string]any) (string, error)
- func GenerateGoDocsComments(pkgName ...string)
- func GenerateJsonDocs(entryDocsFile ...string)
- func GenerateUUID() (string, error)
- func GetPrivateIp() string
- func Graceful(f func() error) error
- func Gzip() func(http.Handler) http.Handler
- func IgnoreLogsEndpoints(pathContain ...string)
- func Limiter(conf *ConfigLimiter) func(http.Handler) http.Handler
- func Logs(callback ...func(method, path, remote string, status int, took time.Duration)) func(http.Handler) http.Handler
- func NewFuncMap(funcMap map[string]any)
- func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error)
- func SaveRawHtml(templateRaw string, templateName string)
- func SetSSLEmail(email string)
- func SetSSLMode(ProdOrDev string)
- func SliceContains[T comparable](elems []T, vs ...T) bool
- func StringContains(s string, subs ...string) bool
- func ToSlug(s string) (string, error)
- func UpgradeConnection(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*ws.Conn, error)
- type ConfigLimiter
- type Context
- func (c *Context) AddHeader(key, value string)
- func (c *Context) AddSSEHeaders()
- func (c *Context) BindBody(strctPointer any, isXML ...bool) error
- func (c *Context) BodyJson() map[string]any
- func (c *Context) BodyText() string
- func (c *Context) Context() context.Context
- func (c *Context) DeleteCookie(key string)
- func (c *Context) DeleteFile(path string) error
- func (c *Context) Download(data_bytes []byte, asFilename string)
- func (c *Context) EarlyHint(hints ...EarlyHint)
- func (c *Context) Error(code int, message string)
- func (c *Context) Flush() bool
- func (c *Context) GetCookie(key string) (string, error)
- func (c *Context) GetKey(key string) (any, bool)
- func (c *Context) GetUserIP() string
- func (c *Context) Html(template_name string, data map[string]any)
- func (c *Context) IsAuthenticated(key ...string) bool
- func (c *Context) Json(data any)
- func (c *Context) JsonIndent(data any)
- func (c *Context) MatchedPath() string
- func (c *Context) NamedRawHtml(rawTemplateName string, data map[string]any) error
- func (c *Context) Param(name string) string
- func (c *Context) ParseMultipartForm(size ...int64) (formData url.Values, formFiles map[string][]*multipart.FileHeader)
- func (c *Context) QueryParam(name string) string
- func (c *Context) RawHtml(rawTemplate string, data map[string]any) error
- func (c *Context) Redirect(path string)
- func (c *Context) SaveFile(fileheader *multipart.FileHeader, path string) error
- func (c *Context) ServeEmbededFile(content_type string, embed_file []byte)
- func (c *Context) ServeFile(content_type, path_to_file string)
- func (c *Context) SetCookie(key, value string, maxAge ...time.Duration)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) SetKey(key string, value any)
- func (c *Context) SetStatus(statusCode int)
- func (c *Context) SliceParams() Params
- func (c *Context) Status(code int) *Context
- func (c *Context) Stream(response string) error
- func (c *Context) Text(body string)
- func (c *Context) UpgradeConnection() (*ws.Conn, error)
- func (c *Context) UploadFile(received_filename, folder_out string, acceptedFormats ...string) (string, []byte, error)
- func (c *Context) UploadFiles(received_filenames []string, folder_out string, acceptedFormats ...string) ([]string, [][]byte, error)
- func (c *Context) User(key ...string) (any, bool)
- func (c *Context) WithPushOptions(opts *http.PushOptions)
- type ContextKey
- type DocsGeneralInfo
- type DocsIn
- type DocsOut
- type DocsRoute
- type EarlyHint
- type EarlyHintType
- type GroupRouter
- func (gr *GroupRouter) Delete(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Get(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Head(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Options(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Patch(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Post(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Put(pattern string, handler Handler, origines ...string) *Route
- func (gr *GroupRouter) Use(middlewares ...func(Handler) Handler)
- type Handler
- type Param
- type Params
- type Route
- func (r *Route) Accept(accept string) *Route
- func (r *Route) Description(description string) *Route
- func (r *Route) In(docsParam ...string) *Route
- func (r *Route) Out(sucessResponse string, failureResponses ...string) *Route
- func (r *Route) Produce(produce string) *Route
- func (r *Route) Summary(summary string) *Route
- func (r *Route) Tags(tags ...string) *Route
- type Router
- func (router *Router) CreateServerCerts(domainName string, subDomains ...string) (*autocert.Manager, *tls.Config)
- func (r *Router) Delete(path string, handler Handler, origines ...string) *Route
- func (router *Router) EmbededStatics(embeded embed.FS, pathLocalDir, webPath string, ...) error
- func (router *Router) EmbededTemplates(template_embed embed.FS, rootDir string) error
- func (router *Router) EnableDomainCheck()
- func (r *Router) Get(path string, handler Handler, origines ...string) *Route
- func (router *Router) Group(prefix string) *GroupRouter
- func (r *Router) Handle(method, path string, handler Handler, origines ...string) *Route
- func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc, origines ...string) *Route
- func (r *Router) Head(path string, handler Handler, origines ...string) *Route
- func (router *Router) LocalStatics(dirPath, webPath string, handlerMiddlewares ...func(handler Handler) Handler) error
- func (router *Router) LocalTemplates(pathToDir string) error
- func (r *Router) Lookup(method, path string) (Handler, Params, bool, string)
- func (router *Router) NewFuncMap(funcMap map[string]any)
- func (router *Router) NewTemplateFunc(funcName string, function any)
- func (r *Router) Options(path string, handler Handler, origines ...string) *Route
- func (r *Router) Patch(path string, handler Handler, origines ...string) *Route
- func (r *Router) Post(path string, handler Handler, origines ...string) *Route
- func (r *Router) Put(path string, handler Handler, origines ...string) *Route
- func (router *Router) ReverseProxy(host, toURL string) (newRouter *Router)
- func (router *Router) Run(addr string)
- func (router *Router) RunAutoTLS(domainName string, subdomains ...string)
- func (router *Router) RunTLS(addr, cert, certKey string)
- func (router *Router) ServeEmbededFile(file []byte, endpoint, contentType string)
- func (r *Router) ServeFiles(path string, root http.FileSystem)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (router *Router) ServeLocalFile(file, endpoint, contentType string)
- func (router *Router) Use(midws ...func(http.Handler) http.Handler)
- func (router *Router) WithDocs(genJsonDocs bool, genGoDocs ...bool) *Router
- func (router *Router) WithMetrics(httpHandler http.Handler, path ...string)
- func (router *Router) WithPprof(path ...string)
- type StatusRecorder
Constants ¶
This section is empty.
Variables ¶
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 )
var AutoCertRegexHostPolicy = false
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) }) } }
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",
}
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 ¶
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 GenerateGoDocsComments ¶
func GenerateGoDocsComments(pkgName ...string)
func GenerateJsonDocs ¶
func GenerateJsonDocs(entryDocsFile ...string)
func GenerateUUID ¶
func GetPrivateIp ¶
func GetPrivateIp() string
func IgnoreLogsEndpoints ¶ added in v0.0.5
func IgnoreLogsEndpoints(pathContain ...string)
func NewFuncMap ¶ added in v0.0.6
func SaveMultipartFile ¶
func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error)
SaveMultipartFile Save MultipartFile
func SaveRawHtml ¶
SaveRawHtml save templateRaw as templateName to be able to use it like c.RawHtml
func SetSSLEmail ¶ added in v0.2.2
func SetSSLEmail(email string)
func SetSSLMode ¶ added in v0.2.2
func SetSSLMode(ProdOrDev string)
func SliceContains ¶
func SliceContains[T comparable](elems []T, vs ...T) bool
func StringContains ¶
Types ¶
type ConfigLimiter ¶ added in v0.0.7
type Context ¶
type Context struct { http.ResponseWriter *http.Request Params Params // contains filtered or unexported fields }
func (*Context) AddSSEHeaders ¶ added in v0.0.4
func (c *Context) AddSSEHeaders()
func (*Context) BodyJson ¶
BodyJson get json body from request and return map USAGE : data := c.BodyJson(r)
func (*Context) DeleteCookie ¶
DeleteCookie delete cookie with specific key
func (*Context) Download ¶
Download download data_bytes(content) asFilename(test.json,data.csv,...) to the client
func (*Context) IsAuthenticated ¶
func (*Context) JsonIndent ¶
JsonIndent return json indented to the client
func (*Context) MatchedPath ¶
func (*Context) NamedRawHtml ¶
NamedRawHtml render rawTemplateName with data using go engine, make sure to save the html using ksmux.SaveRawHtml outside the handler
func (*Context) ParseMultipartForm ¶
func (*Context) QueryParam ¶
QueryParam get query param
func (*Context) RawHtml ¶
NamedRawHtml render rawTemplateName with data using go engine, make sure to save the html using ksmux.SaveRawHtml outside the handler
func (*Context) Redirect ¶
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 ¶
ServeEmbededFile serve an embeded file from handler
func (*Context) SliceParams ¶
func (*Context) UpgradeConnection ¶ added in v0.0.4
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 (*Context) WithPushOptions ¶ added in v0.1.3
func (c *Context) WithPushOptions(opts *http.PushOptions)
type ContextKey ¶
type ContextKey string
type DocsGeneralInfo ¶
type DocsOut ¶
type EarlyHint ¶ added in v0.2.6
type EarlyHint struct { Type EarlyHintType URL string Rel string }
type EarlyHintType ¶ added in v0.2.6
type EarlyHintType string
var ( EarlyHint_OBJECT EarlyHintType = "object" EarlyHint_IMAGE EarlyHintType = "image" EarlyHint_AUDIO EarlyHintType = "audio" EarlyHint_TRACK EarlyHintType = "track" EarlyHint_VIDEO EarlyHintType = "video" EarlyHint_DOCUMENT EarlyHintType = "document" EarlyHint_EMBED EarlyHintType = "embed" EarlyHint_STYLE EarlyHintType = "style" EarlyHint_SCRIPT EarlyHintType = "script" EarlyHint_FETCH EarlyHintType = "fetch" EarlyHint_FONT EarlyHintType = "font" EarlyHint_WORKER EarlyHintType = "worker" )
type GroupRouter ¶
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).
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 ¶
GetParamsFromCtx get params from ctx for http.Handler
type Route ¶
func (*Route) Description ¶
func (*Route) In ¶
In must be like "name in typePath required 'desc'" or you can use ksmux.DocsIn.String() method
func (*Route) Out ¶
Out must be like "200 {object}/{array}/{string} app1.Account/string 'okifstring'" or you can use ksmux.DocsOut.String() method
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) CreateServerCerts ¶ added in v0.2.2
func (*Router) EmbededStatics ¶
func (*Router) EmbededTemplates ¶
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) Group ¶
func (router *Router) Group(prefix string) *GroupRouter
Group create group path
func (*Router) Handle ¶
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) LocalStatics ¶
func (*Router) LocalTemplates ¶
func (*Router) Lookup ¶
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) NewTemplateFunc ¶
func (*Router) ReverseProxy ¶
func (*Router) RunAutoTLS ¶
RunAutoTLS HTTPS server generate certificates and handle renew
func (*Router) ServeEmbededFile ¶
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) WithDocs ¶
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 ¶
WithMetrics take prometheus handler and serve metrics on path or default /metrics
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)