Documentation ¶
Index ¶
- Variables
- func CtxFinalize(ctx *Context)
- func CtxSetDeadline(ctx *Context, deadline time.Time)
- type Context
- func (c *Context) Deadline() (time.Time, bool)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) Flush()
- func (s Context) Get(key string) any
- func (c *Context) Method() HTTPMethod
- func (c *Context) Next()
- func (c *Context) Params() RequestParams
- func (c *Context) Path() string
- func (c *Context) Protocol() string
- func (c *Context) ProtocolMajor() int
- func (c *Context) ProtocolMinor() int
- func (c *Context) Query() url.Values
- func (c *Context) Request() *http.Request
- func (c *Context) RequestBodyReader() io.ReadCloser
- func (c *Context) RequestContentLength() int64
- func (c *Context) RequestCookie(name string) (*http.Cookie, error)
- func (c *Context) RequestHeaders() http.Header
- func (c *Context) RequestHost() string
- func (c *Context) RequestRawURI() string
- func (c *Context) RequestRemoteAddress() string
- func (c *Context) RequestTLS() *tls.ConnectionState
- func (c *Context) RequestTrailers() http.Header
- func (c *Context) RequestTransferEncoding() []string
- func (c *Context) ResponseWriter() http.ResponseWriter
- func (s Context) Set(key string, value any)
- func (c *Context) SetRequestBodyReader(reader io.Reader)
- func (c *Context) SetRequestBodyUnmarshaller(unmarshaller func(into any) error)
- func (c *Context) SetResponseBodyMarshaller(marshaller func(from any) (io.Reader, error))
- func (c *Context) URL() *url.URL
- func (c *Context) UnmarshalRequestBody(into any) error
- func (c *Context) Value(key any) any
- func (c *Context) Write(bytes []byte) (int, error)
- type HTTPMethod
- type Handler
- type HandlerNode
- type Pattern
- type Redirect
- type RequestParams
- type RouteDescriptor
- type Router
- func (r *Router) All(path string, handlersAndTransformers ...any)
- func (r *Router) Delete(path string, handlersAndTransformers ...any)
- func (r *Router) Get(path string, handlersAndTransformers ...any)
- func (r *Router) Handle(ctx *Context)
- func (r *Router) Head(path string, handlersAndTransformers ...any)
- func (r *Router) Options(path string, handlersAndTransformers ...any)
- func (r *Router) Patch(path string, handlersAndTransformers ...any)
- func (r *Router) Post(path string, handlersAndTransformers ...any)
- func (r *Router) PublicAll(path string, handlersAndTransformers ...any)
- func (r *Router) PublicDelete(path string, handlersAndTransformers ...any)
- func (r *Router) PublicGet(path string, handlersAndTransformers ...any)
- func (r *Router) PublicHead(path string, handlersAndTransformers ...any)
- func (r *Router) PublicOptions(path string, handlersAndTransformers ...any)
- func (r *Router) PublicPatch(path string, handlersAndTransformers ...any)
- func (r *Router) PublicPost(path string, handlersAndTransformers ...any)
- func (r *Router) PublicPut(path string, handlersAndTransformers ...any)
- func (r *Router) Put(path string, handlersAndTransformers ...any)
- func (r *Router) RouteDescriptors() []*RouteDescriptor
- func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)
- func (r *Router) Use(handlersAndTransformers ...any)
- type RouterHandler
- type Transformer
Constants ¶
This section is empty.
Variables ¶
var MaxRequestBodySize int64 = 1024 * 1024 * 10 // 10MB
MaxRequestBodySize is the maximum size of a request body. Changing this value will affect all requests. Set to -1 to disable the limit. If MaxRequestBodySize is set on the context it will override this value. This setting is useful for preventing denial of service attacks. It is not recommended to set this value to -1 unless you know what you are doing!!!
var PrintHandlerErrors = false
Functions ¶
func CtxFinalize ¶
func CtxFinalize(ctx *Context)
CtxFinalize allows libraries to call the finalize method on a context. finalize figures out the final status code, headers, and body for the response. This is nomally called by the router, but can be called by libraries which wish to extend or encapsulate the functionality of Navaros.
func CtxSetDeadline ¶
CtxSetDeadline sets a deadline for the context. This allows libraries to limit the amount of time a handler can take to process a request.
Types ¶
type Context ¶
type Context struct { Status int Headers http.Header Cookies []*http.Cookie Body any MaxRequestBodySize int64 Error error ErrorStack string FinalError error FinalErrorStack string // contains filtered or unexported fields }
Context represents a request and response. Navaros handlers access the request and build the response through the context.
func NewContext ¶
NewContext creates a new Context from go's http.ResponseWriter and http.Request. It also takes a variadic list of handlers. This is useful for creating a new Context outside of a router, and can be used by libraries which wish to extend or encapsulate the functionality of Navaros.
func NewContextWithNode ¶
func NewContextWithNode(res http.ResponseWriter, req *http.Request, firstHandlerNode *HandlerNode) *Context
NewContextWithNode creates a new Context from go's http.ResponseWriter and http.Request. It also takes a HandlerNode - a link in a chain of handlers. This is useful for creating a new Context outside of a router, and can be used by libraries which wish to extend or encapsulate the functionality of Navaros. For example, implementing a custom router.
func NewSubContextWithNode ¶
func NewSubContextWithNode(ctx *Context, firstHandlerNode *HandlerNode) *Context
NewSubContextWithNode creates a new Context from an existing Context. This is useful when you want to create a new Context from an existing one, but with a different handler chain. Note that when the end of the sub context's handler chain is reached, the parent context's handler chain will continue.
func (*Context) Deadline ¶
Deadline returns the deadline of the request. Deadline is part of the go context.Context interface.
func (*Context) Done ¶
func (c *Context) Done() <-chan struct{}
Done added for compatibility with go's context.Context. Alias for UntilFinish(). Done is part of the go context.Context interface.
func (*Context) Err ¶
Err returns the final error of the request. Will be nil if the request is still being served even if an error has occurred. Populated once the request is done. Err is part of the go context.Context interface.
func (*Context) Flush ¶
func (c *Context) Flush()
Flush sends any bytes buffered in the response body to the client. Buffering is controlled by go's http.ResponseWriter.
func (*Context) Method ¶
func (c *Context) Method() HTTPMethod
Method returns the HTTP method of the request.
func (*Context) Next ¶
func (c *Context) Next()
Next calls the next handler in the chain. This is useful for creating middleware style handlers that work on the context before and/or after the responding handler.
func (*Context) Params ¶
func (c *Context) Params() RequestParams
Params returns the parameters of the request. These are defined by the route pattern used to bind each handler, and may be different for each time next is called.
func (*Context) ProtocolMajor ¶
ProtocolMajor returns the major number in http protocol version.
func (*Context) ProtocolMinor ¶
ProtocolMinor returns the minor number in http protocol version.
func (*Context) RequestBodyReader ¶
func (c *Context) RequestBodyReader() io.ReadCloser
RequestBodyReader returns a reader setup to read in the request body. This is useful for streaming the request body, or for middleware which decodes the request body. Without body handling middleware, the request body reader is the only way to access request body data.
func (*Context) RequestContentLength ¶
RequestContentLength returns the length of the request body if provided by the client.
func (*Context) RequestCookie ¶
RequestCookies returns the value of a request cookie by name. Returns nil if the cookie does not exist.
func (*Context) RequestHeaders ¶
RequestHeaders returns the request headers.
func (*Context) RequestHost ¶
RequestHost returns the host of the request. Useful for determining the source of the request.
func (*Context) RequestRawURI ¶
RequestRawURI returns the raw URI of the request. This will be the original value from the request headers.
func (*Context) RequestRemoteAddress ¶
RequestRemoteAddress returns the remote address of the request. Useful for determining the source of the request.
func (*Context) RequestTLS ¶
func (c *Context) RequestTLS() *tls.ConnectionState
RequestTLS returns the TLS connection state of the request if the request is using TLS.
func (*Context) RequestTrailers ¶
RequestTrailers returns the trailing headers of the request if set.
func (*Context) RequestTransferEncoding ¶
RequestTransferEncoding returns the transfer encoding of the request
func (*Context) ResponseWriter ¶
func (c *Context) ResponseWriter() http.ResponseWriter
ResponseWriter returns the underlying http.ResponseWriter object.
func (*Context) SetRequestBodyReader ¶
Allows middleware to intercept the request body reader and replace it with their own. This is useful transformers that re-write the request body in a streaming fashion. It's also useful for transformers that re-encode the request body.
func (*Context) SetRequestBodyUnmarshaller ¶
SetRequestBodyUnmarshaller sets the request body unmarshaller. Middleware that parses request bodies should call this method to set the unmarshaller.
func (*Context) SetResponseBodyMarshaller ¶
SetResponseBodyMarshaller sets the response body marshaller. Middleware that encodes response bodies should call this method to set the marshaller.
func (*Context) UnmarshalRequestBody ¶
UnmarshalRequestBody unmarshals the request body into a given value. Note that is method requires SetRequestBodyUnmarshaller to be called first. This likely is done by middleware for parsing request bodies.
type HTTPMethod ¶
type HTTPMethod string
HTTPMethod represents an HTTP method.
const ( // All represents all HTTP methods. All HTTPMethod = "ALL" // Post represents the HTTP POST method. Post HTTPMethod = "POST" // Get represents the HTTP GET method. Get HTTPMethod = "GET" // Put represents the HTTP PUT method. Put HTTPMethod = "PUT" // Patch represents the HTTP PATCH method. Patch HTTPMethod = "PATCH" // Delete represents the HTTP DELETE method. Delete HTTPMethod = "DELETE" // Options represents the HTTP OPTIONS method. Options HTTPMethod = "OPTIONS" // Head represents the HTTP HEAD method. Head HTTPMethod = "HEAD" )
func HTTPMethodFromString ¶
func HTTPMethodFromString(method string) HTTPMethod
HTTPMethodFromString converts a string to an HTTPMethod. If the string is not a valid HTTP method, an error is returned.
type Handler ¶
type Handler interface {
Handle(ctx *Context)
}
Handler is a handler object interface. Any object that implements this interface can be used as a handler in a handler chain.
type HandlerNode ¶
type HandlerNode struct { Method HTTPMethod Pattern *Pattern HandlersAndTransformers []any Next *HandlerNode }
HandlerNode is used to build the handler chains used by the context. The router builds a chain from these objects then attaches them to the context. It then calls Next on the context to execute the chain.
type Pattern ¶
type Pattern struct {
// contains filtered or unexported fields
}
Pattern is used to compare and match request paths to route patterns. Patterns are used by the router to determine which handlers to execute for a given request.
func NewPattern ¶
NewPattern creates a new pattern from a string. The string should be a valid route pattern. If the string is not a valid route pattern, an error is returned.
func (*Pattern) Match ¶
func (p *Pattern) Match(path string) (RequestParams, bool)
Match compares a path to the pattern and returns a map of named parameters extracted from the path as per the pattern. If the path matches the pattern, the second return value will be true. If the path does not match the pattern, the second return value will be false.
type Redirect ¶
type Redirect struct {
To string
}
Redirect represents an HTTP redirect. If you want to redirect a request in a handler, you can initialize a Redirect with a target relative path or absolute URL, and set it as the body of the context. This will cause Navaros to send the client a Location header with the redirect url, and a 302 status code. The status code can be changed by setting the Status field of the context.
type RequestParams ¶
RequestParams represents the parameters extracted from the request path. Parameters are extracted from the path by matching the request path to the route pattern for the handler node. These may change each time Next is called on the context.
func (RequestParams) Get ¶
func (p RequestParams) Get(key string) string
Get returns the value of a given parameter key. If the key does not exist, an empty string is returned.
type RouteDescriptor ¶
type RouteDescriptor struct { Method HTTPMethod Pattern *Pattern }
RouteDescriptor is a struct that is generated by the router when the public variants of the handler binding methods (named after their respective http method) are called. The router has a RouteDescriptors method which returns these objects, and can be used to build a api map, or pre-filter requests before they are passed to the router. This is most useful for libraries that wish to extend the functionality of Navaros.
func (*RouteDescriptor) MarshalJSON ¶
func (r *RouteDescriptor) MarshalJSON() ([]byte, error)
MarshalJSON returns the JSON representation of the route descriptor.
func (*RouteDescriptor) UnmarshalJSON ¶
func (r *RouteDescriptor) UnmarshalJSON(data []byte) error
UnmarshalJSON parses the JSON representation of the route descriptor.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is the main component of Navaros. It is an HTTP handler that can be used to handle requests, and route them to the appropriate handlers. It implements the http.Handler interface, and can be used as a handler in standard http servers. It also implements Navaros' own Handler interface, which allows nesting routers for better code organization.
func (*Router) Delete ¶
Delete allows binding handlers to the DELETE HTTP method at a given route path pattern.
func (*Router) Get ¶
Get allows binding handlers to the GET HTTP method at a given route path pattern.
func (*Router) Handle ¶
Handle is for the purpose of taking an existing context, and running it through the mux's handler chain. If the last handler calls next, it will call next on the original context.
func (*Router) Head ¶
Head allows binding handlers to the HEAD HTTP method at a given route path pattern.
func (*Router) Options ¶
Options allows binding handlers to the OPTIONS HTTP method at a given route path pattern.
func (*Router) Patch ¶
Patch allows binding handlers to the PATCH HTTP method at a given route path pattern.
func (*Router) Post ¶
Post allows binding handlers to the POST HTTP method at a given route path pattern.
func (*Router) PublicAll ¶
PublicAll is the same as All, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicDelete ¶
PublicDelete is the same as Delete, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicGet ¶
PublicGet is the same as Get, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicHead ¶
PublicHead is the same as Head, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicOptions ¶
PublicOptions is the same as Options, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicPatch ¶
PublicPatch is the same as Patch, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicPost ¶
PublicPost is the same as Post, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) PublicPut ¶
PublicPut is the same as Put, but it also adds the route descriptor to the router's list of public route descriptors.
func (*Router) Put ¶
Put allows binding handlers to the PUT HTTP method at a given route path pattern.
func (*Router) RouteDescriptors ¶
func (r *Router) RouteDescriptors() []*RouteDescriptor
RouteDescriptors returns a list of all the route descriptors that this router is responsible for. Useful for gateway configuration.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)
ServeHTTP allows the router to be used as a handler in standard go http servers. It handles the incoming request - creating a context and running the handler chain over it, then finalizing the response.
func (*Router) Use ¶
Use is for middleware handlers. It allows the handlers to be executed on every request. If a path is provided, the middleware will only be executed on requests that match the path.
Note that routers are middleware handlers, and so can be passed to Use to attach them as sub-routers. It's also important to know that if you provide a path with a router, the router will set the mount path as the base path for all of it's handlers. This means that if you have a router with a path of "/foo", and you bind a handler with a path of "/bar", the handler will only be executed on requests with a path of "/foo/bar".
type RouterHandler ¶
type RouterHandler interface { RouteDescriptors() []*RouteDescriptor Handle(ctx *Context) }
RouterHandler is handled nearly identically to a Handler, but it also provides a list of route descriptors which are collected by the router. These will be merged with the other route descriptors already collected. This use for situation where a handler may do more sub-routing, and the allows the handler to report the sub-routes to the router, rather than it's base path.
type Transformer ¶
Transformer is a special type of handler object that can be used to transform the context before and after handlers have processed the request. This is most useful for modifying or re-encoding the request and response bodies.