Documentation
¶
Overview ¶
Package navaros is a lightweight, flexible HTTP router for Go.
It provides powerful route matching, middleware support, and efficient request handling with zero external dependencies. Designed for simplicity and performance, Navaros implements the standard http.Handler interface and supports nested routers, parameterized routes, streaming bodies, and context cancellation.
Quick Start ¶
router := navaros.NewRouter()
router.Get("/users/:id", func(ctx *navaros.Context) {
id := ctx.Params().Get("id")
ctx.Status = 200
ctx.Body = map[string]string{"id": id}
})
http.ListenAndServe(":8080", router)
Features ¶
- Sequential pattern matching with regex for dynamic segments - Middleware chain with Next() for pre/post processing - Parameter extraction with wildcards, regex, optional/greedy modifiers - JSON body parsing via middleware - Panic recovery and error handling - Context implements context.Context for cancellation - Nestable sub-routers for modular code - Streaming request/response bodies - No dependencies beyond stdlib
Middleware ¶
Use middleware for auth, logging, body parsing:
router.Use(func(ctx *navaros.Context) {
// Pre-handler logic
ctx.Next()
// Post-handler logic
})
Built-in JSON middleware: import "github.com/RobertWHurst/navaros/middleware/json"; router.Use(json.Middleware(nil))
Route Patterns ¶
- Static: /users - Param: /users/:id - Wildcard: /files/* - Optional: /users/:id? - Regex: /users/:id(\\d+) - Combine: /api/:v(\\d+)/:action*/static
Specific patterns before general.
Context ¶
Unified access to request/response/params:
ctx.Params().Get("id") ctx.UnmarshalRequestBody(&user) ctx.Status = 200 ctx.Body = user
Supports Set/Get for per-request data.
See https://pkg.go.dev/github.com/RobertWHurst/navaros for full API docs.
Index ¶
- Variables
- func CtxDeleteParam(ctx *Context, key string)
- func CtxFinalize(ctx *Context)
- func CtxFree(ctx *Context)
- func CtxInhibitResponse(ctx *Context)
- func CtxSetDeadline(ctx *Context, deadline time.Time)
- func CtxSetParam(ctx *Context, key, value string)
- func SetPrintHandlerErrors(enable bool)
- type Context
- func (c *Context) Close() error
- func (c *Context) Deadline() (time.Time, bool)
- func (c *Context) Delete(key string)
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) Flush()
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) Method() HTTPMethod
- func (c *Context) MustGet(key string) any
- 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) ResponseStatus() int
- func (c *Context) ResponseWriter() http.ResponseWriter
- func (c *Context) Set(key string, value any)
- func (c *Context) SetRequestBodyReader(reader io.Reader)
- func (c *Context) SetRequestBodyUnmarshaller(unmarshaller func(ctx *Context, into any) error)
- func (c *Context) SetResponseBodyMarshaller(marshaller func(ctx *Context, from any) (io.Reader, error))
- func (c *Context) URL() *url.URL
- func (c *Context) UnmarshalRequestBody(into any) error
- func (c *Context) Value(any) any
- func (c *Context) Write(bytes []byte) (int, error)
- type ContextResponseWriter
- type HTTPMethod
- type Handler
- type HandlerFunc
- type HandlerNode
- type MetadataOption
- type Pattern
- type Redirect
- type RequestParams
- type RouteDescriptor
- type RouteOption
- 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) Lookup(handlerOrTransformer any) (HTTPMethod, *Pattern, bool)
- 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 CtxDeleteParam ¶ added in v1.8.2
CtxDeleteParam allows tests to delete a parameter from the context.
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 normally called by the router, but can be called by libraries which wish to extend or encapsulate the functionality of Navaros.
func CtxFree ¶ added in v1.8.0
func CtxFree(ctx *Context)
CtxFree allows libraries to free a context they created manually. This is important, DO NOT FORGET TO CALL THIS IF YOU CREATE A CONTEXT MANUALLY.
func CtxInhibitResponse ¶
func CtxInhibitResponse(ctx *Context)
CtxInhibitResponse prevents the context from sending a response. This is useful for libraries which wish to handle the response themselves. For example, a upgraded websocket connection cannot have response headers written to it.
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.
func CtxSetParam ¶ added in v1.8.2
CtxGetParam enables tests to set parameters on a context. This is needed because tests often use NewContext to create a context to use with the handler being tested. Because the context wasn't matched against a real path, it will have no parameters. This function allows tests to set parameters on the context.
func SetPrintHandlerErrors ¶ added in v1.5.2
func SetPrintHandlerErrors(enable bool)
SetPrintHandlerErrors toggles the printing of handler errors.
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 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 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) Close ¶ added in v1.5.0
Close simply aliases Flush. It's implemented to satisfy the io.Closer interface.
func (*Context) Deadline ¶
Deadline returns the deadline of the request. Deadline is part of the go context.Context interface. This method is thread-safe.
func (*Context) Delete ¶ added in v1.13.0
Delete removes a value attached to the context with Set. This method is thread-safe.
func (*Context) Done ¶
func (c *Context) Done() <-chan struct{}
Done added for compatibility with go's context.Context. Done is part of the go context.Context interface. Returns a channel that will be closed once the response has been finalized and sent to the client, or if if the request has been aborted. This method is thread-safe.
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. This method is thread-safe.
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) Get ¶
Get retrieves a value attached to the context with Set. This method is thread-safe.
func (*Context) Method ¶
func (c *Context) Method() HTTPMethod
Method returns the HTTP method of the request.
func (*Context) MustGet ¶ added in v1.12.0
MustGet retrieves a value attached to the context with Set. It panics if the value does not exist. This method is thread-safe.
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. This method is thread-safe and returns a copy of the params map.
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 ¶
RequestCookie 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) ResponseStatus ¶ added in v1.7.0
ResponseStatus returns the HTTP status code that will be sent to the client given the state of the body and status properties. This is useful for middleware that needs to check what the status code will be before the response is finalized.
func (*Context) ResponseWriter ¶
func (c *Context) ResponseWriter() http.ResponseWriter
ResponseWriter returns the underlying http.ResponseWriter object.
func (*Context) Set ¶
Set attaches a value to the context. It can later be retrieved with Get. This method is thread-safe.
func (*Context) SetRequestBodyReader ¶
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 ¶
func (c *Context) SetResponseBodyMarshaller(marshaller func(ctx *Context, from any) (io.Reader, error))
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 ContextResponseWriter ¶ added in v1.5.2
type ContextResponseWriter struct {
// contains filtered or unexported fields
}
func (*ContextResponseWriter) Header ¶ added in v1.5.2
func (c *ContextResponseWriter) Header() http.Header
func (*ContextResponseWriter) Hijack ¶ added in v1.14.4
func (c *ContextResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
func (*ContextResponseWriter) Write ¶ added in v1.5.2
func (c *ContextResponseWriter) Write(bytes []byte) (int, error)
func (*ContextResponseWriter) WriteHeader ¶ added in v1.5.2
func (c *ContextResponseWriter) WriteHeader(status int)
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, error)
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 HandlerFunc ¶
type HandlerFunc func(ctx *Context)
HandlerFunc is a function that can be used as a handler with Navaros.
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 MetadataOption ¶ added in v1.17.0
type MetadataOption struct {
// contains filtered or unexported fields
}
MetadataOption is a RouteOption that carries arbitrary metadata to be attached to the route descriptor.
func WithMetadata ¶ added in v1.17.0
func WithMetadata(value any) MetadataOption
WithMetadata creates a RouteOption that attaches arbitrary metadata to the route descriptor. This metadata can be used by gateways and middleware to implement features like rate limiting, auth requirements, etc.
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.
func (*Pattern) MatchInto ¶
func (p *Pattern) MatchInto(path string, params *RequestParams) bool
MatchInto takes a path and a request params map and extracts the named parameters from the path into the map if the path matches the pattern. True will also be returned. If the path does not match the pattern, false will be returned, and no changes will be made to the map.
func (*Pattern) Path ¶ added in v1.9.0
func (p *Pattern) Path(params RequestParams, wildcards []string) (string, error)
Path creates a path string from the pattern by replacing dynamic segments with the provided parameters. If a required parameter is missing, an error is returned. Optional segments are only included if their parameters are provided. Wildcard segments are replaced with values from the wildcards slice in order. If there are more wildcard segments than values in the slice, an error is returned.
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
Metadata any
}
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 RouteOption ¶ added in v1.17.0
type RouteOption interface {
// contains filtered or unexported methods
}
RouteOption is an interface for options that can be passed alongside handlers and transformers when binding routes. Route options are extracted before handler validation and do not participate in the handler chain.
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) Lookup ¶ added in v1.9.0
func (r *Router) Lookup(handlerOrTransformer any) (HTTPMethod, *Pattern, bool)
Lookup takes a handler or transformer and looks up what HTTP method and route pattern it is bound to. Returns the method, pattern, and true if found, or empty string, nil, and false if not found.
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)
Lookup(handlerOrTransformer any) (HTTPMethod, *Pattern, bool)
}
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.