Documentation ¶
Index ¶
- Variables
- func Crypto() *cryptoShortcuts
- func HashCrc32(content []byte) string
- func HashMD5(text string) string
- func NewKeyring(salt string, iterations int, length int, digest string) *crypto.Keyring
- func NewUID() (uid string)
- func NodeName() string
- func SecretKeyBase() string
- func SecretKeySync(sync SecretKeySyncFunc) (cancel func())
- func SecretKeys() []string
- func SetNodeName(name string)
- func SetSecretKeyBase(secret string) error
- type Context
- func (ctx *Context) AddHeader(key, value string)
- func (ctx *Context) AfterSend(callback func()) error
- func (ctx *Context) BeforeSend(callback func()) error
- func (ctx *Context) DeleteCookie(name string)
- func (ctx *Context) Error(error string, code int)
- func (ctx *Context) Get(key any) any
- func (ctx *Context) GetCookie(name string) *http.Cookie
- func (ctx *Context) GetHeader(key string) string
- func (ctx *Context) GetParam(name string) string
- func (ctx *Context) GetParamByIndex(index int) string
- func (ctx *Context) Header() http.Header
- func (ctx *Context) NewUID() (uid string)
- func (ctx *Context) NotFound()
- func (ctx *Context) Redirect(url string, code int)
- func (ctx *Context) Router() *Router
- func (ctx *Context) Set(key any, value any)
- func (ctx *Context) SetCookie(cookie *http.Cookie)
- func (ctx *Context) SetHeader(key, value string)
- func (ctx *Context) WithParams(names []string, values []string) *Context
- func (ctx *Context) Write(data []byte) (int, error)
- func (ctx *Context) WriteHeader(statusCode int)
- type Group
- type Handle
- type JsonSerializer
- type Middleware
- type MiddlewareHandler
- type MiddlewareWithInitHandler
- type PathDetails
- type Registry
- type ResponseWriterSpy
- type Route
- type RouteConfigurator
- type RouteStorage
- type Router
- func (r *Router) Configure(route string, configurator RouteConfigurator)
- func (r *Router) DELETE(route string, handle any)
- func (r *Router) GET(route string, handle any)
- func (r *Router) GetContext(req *http.Request, w http.ResponseWriter, path string) *Context
- func (r *Router) Group(route string) Group
- func (r *Router) HEAD(route string, handle any)
- func (r *Router) Handle(method string, route string, handle any)
- func (r *Router) Lookup(method string, path string) (*Route, *Context)
- func (r *Router) OPTIONS(route string, handle any)
- func (r *Router) PATCH(route string, handle any)
- func (r *Router) POST(route string, handle any)
- func (r *Router) PUT(route string, handle any)
- func (r *Router) PutContext(ctx *Context)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Use(args ...any) Group
- type RouterGroup
- func (r *RouterGroup) Configure(route string, configurator RouteConfigurator)
- func (r *RouterGroup) DELETE(route string, handle any)
- func (r *RouterGroup) GET(route string, handle any)
- func (r *RouterGroup) Group(route string) Group
- func (r *RouterGroup) HEAD(route string, handle any)
- func (r *RouterGroup) Handle(method string, route string, handle any)
- func (r *RouterGroup) OPTIONS(route string, handle any)
- func (r *RouterGroup) PATCH(route string, handle any)
- func (r *RouterGroup) POST(route string, handle any)
- func (r *RouterGroup) PUT(route string, handle any)
- func (r *RouterGroup) Use(args ...any) Group
- type SecretKeySyncFunc
- type Serializer
Constants ¶
This section is empty.
Variables ¶
var AlreadySentError = errors.New("the response was already sent")
AlreadySentError Error raised when trying to modify or send an already sent response
var ContextKey = chainContextKey{}
ContextKey is the request context key under which URL params are stored.
Functions ¶
func Crypto ¶
func Crypto() *cryptoShortcuts
Crypto get the reference to a structure that has shortcut to all encryption related functions
func NewKeyring ¶
NewKeyring starts a Keyring that will be updated whenever SecretKeySync() is invoked
- `salt` - a salt used with SecretKeyBase to generate a secret
- `iterations` - defaults to 1000 (increase to at least 2^16 if used for passwords)
- `length` - a length in octets for the derived key. Defaults to 32
- `digest` - a hmac function to use as the pseudo-random function. Defaults to `sha256`
func SecretKeyBase ¶
func SecretKeyBase() string
SecretKeyBase A secret key used to verify and encrypt data.
This data must be never used directly, always use chain.Crypto().KeyGenerate() to derive keys from it
func SecretKeySync ¶
func SecretKeySync(sync SecretKeySyncFunc) (cancel func())
SecretKeySync is used to transmit SecretKeyBase changes
func SecretKeys ¶
func SecretKeys() []string
SecretKeys gets the list of all SecretKeyBase that have been defined. Can be used in key rotation algorithms
The LAST item in the list is the most recent key (primary key)
func SetNodeName ¶
func SetNodeName(name string)
func SetSecretKeyBase ¶
SetSecretKeyBase see SecretKeyBase()
Types ¶
type Context ¶
type Context struct { MatchedRoutePath string Writer http.ResponseWriter Request *http.Request Crypto *cryptoShortcuts // contains filtered or unexported fields }
Context represents a request & response Context.
func GetContext ¶
GetContext pulls the URL parameters from a request context, or returns nil if none are present.
func (*Context) AddHeader ¶
AddHeader adds the key, value pair to the header. It appends to any existing values associated with key. The key is case insensitive; it is canonicalized by CanonicalHeaderKey.
func (*Context) BeforeSend ¶
BeforeSend Registers a callback to be invoked before the response is sent.
Callbacks are invoked in the reverse order they are defined (callbacks defined first are invoked last).
func (*Context) DeleteCookie ¶
DeleteCookie delete a cookie by name
func (*Context) Error ¶
Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.
func (*Context) GetCookie ¶
GetCookie returns the named cookie provided in the request or nil if not found. If multiple cookies match the given name, only one cookie will be returned.
func (*Context) GetHeader ¶
GetHeader gets the first value associated with the given key. If there are no values associated with the key, GetHeader returns "". It is case insensitive; textproto.CanonicalMIMEHeaderKey is used to canonicalize the provided key. Get assumes that all keys are stored in canonical form. To use non-canonical keys, access the map directly.
func (*Context) GetParam ¶
GetParam returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.
func (*Context) GetParamByIndex ¶
GetParamByIndex get one parameter per index
func (*Context) Header ¶
Header returns the header map that will be sent by WriteHeader. The Header map also is the mechanism with which Handlers can set HTTP trailers.
Changing the header map after a call to WriteHeader (or Write) has no effect unless the HTTP status code was of the 1xx class or the modified headers are trailers.
There are two ways to set Trailers. The preferred way is to predeclare in the headers which trailers you will later send by setting the "Trailer" header to the names of the trailer keys which will come later. In this case, those keys of the Header map are treated as if they were trailers. See the example. The second way, for trailer keys not known to the Handle until after the first Write, is to prefix the Header map keys with the TrailerPrefix constant value. See TrailerPrefix.
To suppress automatic response headers (such as "Date"), set their value to nil.
func (*Context) NewUID ¶
NewUID get a new KSUID.
KSUID is for K-Sortable Unique IDentifier. It is a kind of globally unique identifier similar to a RFC 4122 UUID, built from the ground-up to be "naturally" sorted by generation timestamp without any special type-aware logic.
func (*Context) NotFound ¶
func (ctx *Context) NotFound()
NotFound replies to the request with an HTTP 404 not found error.
func (*Context) Redirect ¶
Redirect replies to the request with a redirect to url, which may be a path relative to the request path.
The provided code should be in the 3xx range and is usually StatusMovedPermanently, StatusFound or StatusSeeOther.
If the Content-Type header has not been set, Redirect sets it to "text/html; charset=utf-8" and writes a small HTML body.
Setting the Content-Type header to any value, including nil, disables that behavior.
func (*Context) SetCookie ¶
SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*Context) SetHeader ¶
SetHeader sets the header entries associated with key to the single element value. It replaces any existing values associated with key. The key is case insensitive; it is canonicalized by textproto.CanonicalMIMEHeaderKey. To use non-canonical keys, assign to the map directly.
func (*Context) WithParams ¶
func (*Context) Write ¶
Write writes the data to the connection as part of an HTTP reply.
If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) before writing the data. If the Header does not contain a Content-Type line, Write adds a Content-Type set to the result of passing the initial 512 bytes of written data to DetectContentType. Additionally, if the total size of all written data is under a few KB and there are no Flush calls, the Content-Length header is added automatically.
Depending on the HTTP protocol version and the client, calling Write or WriteHeader may prevent future reads on the Request.Body. For HTTP/1.x requests, handlers should read any needed request body data before writing the response. Once the headers have been flushed (due to either an explicit Flusher.Flush call or writing enough data to trigger a flush), the request body may be unavailable. For HTTP/2 requests, the Go HTTP server permits handlers to continue to read the request body while concurrently writing the response. However, such behavior may not be supported by all HTTP/2 clients. Handlers should read before writing if possible to maximize compatibility.
func (*Context) WriteHeader ¶
WriteHeader sends an HTTP response header with the provided status code.
If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes or 1xx informational responses.
The provided code must be a valid HTTP 1xx-5xx status code. Any number of 1xx headers may be written, followed by at most one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx headers may be buffered. Use the Flusher interface to send buffered data. The header map is cleared when 2xx-5xx headers are sent, but not with 1xx headers.
The server will automatically send a 100 (Continue) header on the first read from the request body if the request has an "Expect: 100-continue" header.
type Group ¶
type Group interface { GET(route string, handle any) HEAD(route string, handle any) OPTIONS(route string, handle any) POST(route string, handle any) PUT(route string, handle any) PATCH(route string, handle any) DELETE(route string, handle any) Use(args ...any) Group Group(route string) Group Handle(method string, route string, handle any) Configure(route string, configurator RouteConfigurator) }
type JsonSerializer ¶
type JsonSerializer struct { }
type Middleware ¶
type Middleware struct { Path *PathDetails Handle func(ctx *Context, next func() error) error }
type MiddlewareHandler ¶
type PathDetails ¶
type PathDetails struct {
// contains filtered or unexported fields
}
PathDetails represents all useful information about a dynamic path (used by handlers)
func ParsePathDetails ¶
func ParsePathDetails(pathOrig string) *PathDetails
ParsePathDetails obtém informações sobre um path dinamico.
func (PathDetails) FastMatch ¶
func (d PathDetails) FastMatch(ctx *Context) bool
func (PathDetails) Match ¶
func (d PathDetails) Match(ctx *Context) (match bool, paramNames []string, paramValues []string)
Match checks if the patch is compatible, performs the extraction of parameters
func (PathDetails) MaybeMatches ¶
func (d PathDetails) MaybeMatches(o *PathDetails) bool
MaybeMatches checks if this path is applicable over the other. Used for registering middlewares in routes
func (PathDetails) ReplacePath ¶
func (d PathDetails) ReplacePath(ctx *Context) string
func (PathDetails) String ¶
func (d PathDetails) String() string
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry is an algorithm-independent framework for recording routes. This division allows us to explore different algorithms without breaking the contract.
type ResponseWriterSpy ¶
type ResponseWriterSpy struct { http.ResponseWriter // contains filtered or unexported fields }
func (*ResponseWriterSpy) WriteHeader ¶
func (w *ResponseWriterSpy) WriteHeader(status int)
type Route ¶
type Route struct { Path *PathDetails Handle Handle Middlewares []*Middleware // contains filtered or unexported fields }
Route control of a registered route
type RouteConfigurator ¶
type RouteStorage ¶
type RouteStorage struct {
// contains filtered or unexported fields
}
type Router ¶
type Router struct { Crypto cryptoShortcuts // 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 handle 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 handle 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 automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS 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 NotFoundHandler handler. HandleMethodNotAllowed bool // Configurable http.Handler function which is called when no matching route is found. If it is not set, http.NotFound is // used. NotFoundHandler http.Handler // Configurable http.Handler function 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. MethodNotAllowedHandler http.Handler // An optional http.Handler function 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. GlobalOPTIONSHandler http.Handler // Function to handle errors recovered from http handlers and middlewares. // The handler can be used to do global error handling (not handled in middlewares) ErrorHandler func(*Context, error) // 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, any) // contains filtered or unexported fields }
Router is a high-performance router.
func (*Router) Configure ¶
func (r *Router) Configure(route string, configurator RouteConfigurator)
Configure allows a RouteConfigurator to perform route configurations
func (*Router) DELETE ¶
DELETE is a shortcut for router.handleFunc(http.MethodDelete, Route, handle)
func (*Router) GetContext ¶
GetContext returns a new ContextImpl from the pool.
func (*Router) Lookup ¶
Lookup finds the Route and parameters for the given Route and assigns them to the given Context.
func (*Router) OPTIONS ¶
OPTIONS is a shortcut for router.handleFunc(http.MethodOptions, Route, handle)
func (*Router) PutContext ¶
PutContext Close frees up resources and is automatically called in the ServeHTTP part of the web server.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP responds to the given request.
func (*Router) Use ¶
Use registers a middleware routeT that will match requests with the provided prefix (which is optional and defaults to "/*").
router.Use(func(ctx *chain.Context) error { return ctx.NextFunc() }) router.Use(firstMiddleware, secondMiddleware) app.Use("/api", func(ctx *chain.Context) error { return ctx.NextFunc() }) app.Use("GET", "/api", func(ctx *chain.Context) error { return ctx.NextFunc() }) app.Use("GET", "/files/*filepath", func(ctx *chain.Context) error { println(ctx.GetParam("filepath")) return ctx.NextFunc() })
type RouterGroup ¶
type RouterGroup struct {
// contains filtered or unexported fields
}
func (*RouterGroup) Configure ¶
func (r *RouterGroup) Configure(route string, configurator RouteConfigurator)
func (*RouterGroup) DELETE ¶
func (r *RouterGroup) DELETE(route string, handle any)
func (*RouterGroup) GET ¶
func (r *RouterGroup) GET(route string, handle any)
func (*RouterGroup) Group ¶
func (r *RouterGroup) Group(route string) Group
func (*RouterGroup) HEAD ¶
func (r *RouterGroup) HEAD(route string, handle any)
func (*RouterGroup) OPTIONS ¶
func (r *RouterGroup) OPTIONS(route string, handle any)
func (*RouterGroup) PATCH ¶
func (r *RouterGroup) PATCH(route string, handle any)
func (*RouterGroup) POST ¶
func (r *RouterGroup) POST(route string, handle any)
func (*RouterGroup) PUT ¶
func (r *RouterGroup) PUT(route string, handle any)
func (*RouterGroup) Use ¶
func (r *RouterGroup) Use(args ...any) Group
type SecretKeySyncFunc ¶
type SecretKeySyncFunc func(key string)