Documentation ¶
Overview ¶
The router package provides a simple interface that maps routes to handlers. The router accepts a type argument which must implement the Action interface. This allows clients to define extend and enhance the BaseAction type with additional data and functionality.
Example:
package main type MyAction struct { requestId string *router.BaseAction } func Run() { // Router that defines a context creator that returns a new MyAction for each request. router := New(func(ac *MyAction) { ac.requestId = randomString() })) // Add an Around handler that sets the requestId header router.Around(func(ac *MyAction, next func()) { ac.Response.Header().Add("X-Request-ID", ac.requestId) next() }) // Echo back the requestId header router.Get("/echo", func(ac *MyAction) { ac.Write([]byte(ac.requestId)) }) http.ListenAndServe(":8080", router) }
Index ¶
- type BeforeFunc
- type HandlerFunc
- type Middleware
- type Next
- type NoData
- type Request
- func (r Request[Data]) Body() io.ReadCloser
- func (r Request[Data]) ContentLength() int64
- func (r Request[Data]) Cookie(name string) (*http.Cookie, error)
- func (r Request[Data]) Cookies() []*http.Cookie
- func (r Request[Data]) FormData() (map[string][]string, error)
- func (r Request[Data]) FormValue(key string) string
- func (r Request[Data]) Header() http.Header
- func (r Request[Data]) Host() string
- func (r Request[Data]) MatchedPath() string
- func (r Request[Data]) Method() string
- func (r Request[Data]) Params() map[string]string
- func (r Request[Data]) PostFormData() (map[string][]string, error)
- func (r Request[Data]) Proto() string
- func (r Request[Data]) ProtoMajor() int
- func (r Request[Data]) ProtoMinor() int
- func (r Request[Data]) Query() url.Values
- func (r Request[Data]) QueryParam(name string) string
- func (r Request[Data]) QueryParams(name string) []string
- func (r Request[Data]) Referer() string
- func (r Request[Data]) RemoteAddr() string
- func (r Request[Data]) Request() *http.Request
- func (r Request[Data]) RequestURI() string
- func (r Request[Data]) URL() *url.URL
- type Response
- type ResponseBuilder
- func (rb *ResponseBuilder) Body() io.Reader
- func (rb *ResponseBuilder) Header() http.Header
- func (rb *ResponseBuilder) Status() int
- func (rb *ResponseBuilder) Write(p []byte) (int, error)
- func (rb *ResponseBuilder) WriteStatus(status int)
- func (rb *ResponseBuilder) WriteString(s string) (int, error)
- type RootRequest
- type Route
- type RouteData
- type RouteGroup
- func Group[ParentData any, Data any, Parent registerable[ParentData]](parent Parent, creator func(r *Request[ParentData]) Data) *RouteGroup[ParentData, Data]
- func GroupWithContext[ParentData any, Data any, Parent registerable[ParentData]](parent Parent, ...) *RouteGroup[ParentData, Data]
- func SubRouter[ParentData any, Data any, Parent registerable[ParentData]](parent Parent, prefix string, creator func(r *Request[ParentData]) Data) *RouteGroup[ParentData, Data]
- func SubRouterWithContext[ParentData any, Data any, Parent registerable[ParentData]](parent Parent, prefix string, ...) *RouteGroup[ParentData, Data]
- func (r *RouteGroup[ParentData, Data]) Before(before BeforeFunc[Data])
- func (g *RouteGroup[ParentData, Data]) Delete(path string, handler HandlerFunc[Data])
- func (g *RouteGroup[ParentData, Data]) Get(path string, handler HandlerFunc[Data])
- func (g *RouteGroup[ParentData, Data]) Match(method string, path string, handler HandlerFunc[Data])
- func (g *RouteGroup[ParentData, Data]) Patch(path string, handler HandlerFunc[Data])
- func (g *RouteGroup[ParentData, Data]) Post(path string, handler HandlerFunc[Data])
- func (t *RouteGroup[ParentData, Data]) Put(path string, handler HandlerFunc[Data])
- type Router
- func (r *Router[T]) Before(before BeforeFunc[T])
- func (r *Router[T]) Delete(path string, handler HandlerFunc[T])
- func (r *Router[T]) Get(path string, handler HandlerFunc[T])
- func (r *Router[T]) Match(method string, path string, handler HandlerFunc[T])
- func (r *Router[T]) Missing(handler HandlerFunc[T])
- func (r *Router[T]) Patch(path string, handler HandlerFunc[T])
- func (r *Router[T]) Post(path string, handler HandlerFunc[T])
- func (r *Router[T]) Put(path string, handler HandlerFunc[T])
- func (router *Router[T]) ServeHTTP(rw http.ResponseWriter, r *http.Request)
- func (r *Router[T]) Use(middleware Middleware)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type BeforeFunc ¶
BeforeFunc is a function that is called before the action is executed.
type HandlerFunc ¶
A function that handles a request.
type Middleware ¶
type Middleware func(http.ResponseWriter, *http.Request, http.HandlerFunc)
Middleware is a function that is called before the action is executed. See Router.Use for more information. type Middleware func(c Action, next HandlerFunc[Action])
type Next ¶
Next is a function that calls the next BeforeFunc or HandlerFunc in the chain. It accepts a context and returns a Response.
type NoData ¶
type NoData struct{}
NoData is a placeholder type for the default action creator.
func WithNoData ¶
func WithNoData(rootRequest *RootRequest) NoData
WithNoData is a convenience function for creating a NoData type for use with groups and routers.
type Request ¶
type Request[Data any] struct { Data Data // contains filtered or unexported fields }
Request is a wrapper around http.Request that contains the original Request object and the response writer. It also can contain application specific data that is passed to the handlers.
func NewRequest ¶
func (Request[Data]) Body ¶
func (r Request[Data]) Body() io.ReadCloser
Body returns the request body.
func (Request[Data]) ContentLength ¶
ContentLength returns the length of the request body.
func (Request[Data]) FormValue ¶
FormValue returns the first value for the named component of the request body, ignoring errors from ParseForm.
func (Request[Data]) MatchedPath ¶
MatchedPath returns the route path pattern that was matched.
func (Request[Data]) PostFormData ¶
PostFormData returns the parsed form data from the request body.
func (Request[Data]) ProtoMajor ¶
ProtoMajor returns the HTTP protocol major version of the request.
func (Request[Data]) ProtoMinor ¶
ProtoMinor returns the HTTP protocol minor version of the request.
func (Request[Data]) QueryParam ¶
QueryParam returns the first value for the named component of the query.
func (Request[Data]) QueryParams ¶
QueryParams returns the values for the named component of the query.
func (Request[Data]) RemoteAddr ¶
RemoteAddr returns the remote address of the request.
func (Request[Data]) RequestURI ¶
RequestURI returns the unmodified request-target of the request.
type Response ¶
ResponseWriter is an interface that represents the response that will be sent to the client.
The default status if not provided is 200, and the default headers are an empty map.
func StringResponse ¶
type ResponseBuilder ¶
type ResponseBuilder struct {
// contains filtered or unexported fields
}
ResponseBuilder is a helper struct that can be used to build a response. It implements the response interface and can be returned directly from handlers.
func NewResponse ¶
func NewResponse() *ResponseBuilder
NewResponse returns a new ResponseBuilder that can be used to build a response.
func (*ResponseBuilder) Body ¶
func (rb *ResponseBuilder) Body() io.Reader
Body returns the body of the response.
func (*ResponseBuilder) Header ¶
func (rb *ResponseBuilder) Header() http.Header
Header returns the header map for the response.
func (*ResponseBuilder) Status ¶
func (rb *ResponseBuilder) Status() int
Status returns the status code of the response.
func (*ResponseBuilder) Write ¶
func (rb *ResponseBuilder) Write(p []byte) (int, error)
Write writes the provided bytes to the response body.
func (*ResponseBuilder) WriteStatus ¶
func (rb *ResponseBuilder) WriteStatus(status int)
WriteStatus sets the status code for the response. It does not prevent the status code from being changed by a middleware or writing additional headers.
func (*ResponseBuilder) WriteString ¶
func (rb *ResponseBuilder) WriteString(s string) (int, error)
WriteString writes the provided string to the response body.
type RootRequest ¶
RootRequest is a wrapper around http.Request that contains the original Request object and the response writer. This is used for the root router since there is no application specific data to store.
type Route ¶
A Route is a single route that can be matched against a request and holds a reference to the handler used to handle the reques and holds a reference to the handler used to handle the request.
type RouteData ¶
type RouteData struct { // Params holds the route parameters that were matched. Params map[string]string // HandlerPath holds the path that was matched. HandlerPath string }
RouteData holds data about the matched route.
type RouteGroup ¶
RouteGroup represents a collection of routes that share a common set of Around/Before/After callbacks and Action type (T)
func Group ¶
func Group[ ParentData any, Data any, Parent registerable[ParentData], ]( parent Parent, creator func(r *Request[ParentData]) Data, ) *RouteGroup[ParentData, Data]
NewGroup creates a new route Group that can be used to group around filters and other common behavior.
An action creator function is passed to the NewGroup, so that it can reference fields from the parent action type.
func GroupWithContext ¶
func GroupWithContext[ ParentData any, Data any, Parent registerable[ParentData], ]( parent Parent, creator func(context.Context, *Request[ParentData]) (context.Context, Data), ) *RouteGroup[ParentData, Data]
GroupWithContext has the same behavior as Group but passes the context to the data creator and requires a context to be returned.
func SubRouter ¶
func SubRouter[ ParentData any, Data any, Parent registerable[ParentData], ]( parent Parent, prefix string, creator func(r *Request[ParentData]) Data, ) *RouteGroup[ParentData, Data]
SubRouter creates a new grouping of routes that will be routed to in addition to the routes defined on the primery router. These routes will be prefixed using the given prefix.
Subrouters provide their own action creator, so common behavior can be grouped via a custom action.
Diagram of what the "inheritance" chain can look like:
router[GlobalAction] | |_Group[GlobalAction, LoggedInAction] | |-Group[LoggedInAction, Teams] | |-Group[LoggedInAction, Settings] | |-Group[LoggedInAction, Admin] | |_ Group[Admin, SuperAdmin]
func SubRouterWithContext ¶
func SubRouterWithContext[ ParentData any, Data any, Parent registerable[ParentData], ]( parent Parent, prefix string, creator func(ctx context.Context, r *Request[ParentData]) (context.Context, Data), ) *RouteGroup[ParentData, Data]
SubRouterWithContext has the same behavior as SubRouter but passes the context to the data creator and
func (*RouteGroup[ParentData, Data]) Before ¶
func (r *RouteGroup[ParentData, Data]) Before(before BeforeFunc[Data])
func (*RouteGroup[ParentData, Data]) Delete ¶
func (g *RouteGroup[ParentData, Data]) Delete(path string, handler HandlerFunc[Data])
Defines a new Route that responds to DELETE requests.
func (*RouteGroup[ParentData, Data]) Get ¶
func (g *RouteGroup[ParentData, Data]) Get(path string, handler HandlerFunc[Data])
Defines a new Route that responds to GET requests.
func (*RouteGroup[ParentData, Data]) Match ¶
func (g *RouteGroup[ParentData, Data]) Match(method string, path string, handler HandlerFunc[Data])
Match defines a new Route that responds to requests that match the given method and path.
func (*RouteGroup[ParentData, Data]) Patch ¶
func (g *RouteGroup[ParentData, Data]) Patch(path string, handler HandlerFunc[Data])
Defines a new Route that responds to PATCH requests.
func (*RouteGroup[ParentData, Data]) Post ¶
func (g *RouteGroup[ParentData, Data]) Post(path string, handler HandlerFunc[Data])
Defines a new Route that responds to POST requests.
func (*RouteGroup[ParentData, Data]) Put ¶
func (t *RouteGroup[ParentData, Data]) Put(path string, handler HandlerFunc[Data])
Defines a new Route that responds to PUT requests.
type Router ¶
type Router[T any] struct { // contains filtered or unexported fields }
Router is a collection of Routes and is used to dispatch requests to the correct Route handler.
func New ¶
func New[T any](dataCreator func(*RootRequest) T) *Router[T]
Creates a new Router with the given action creator used to create the application's root type.
func NewWithContext ¶
func NewWithContext[T any](dataCreator func(context.Context, *RootRequest) (context.Context, T)) *Router[T]
NewWithContext behaves the same as New, but is passed a context and expects a context to be returned from the data creator.
func (*Router[T]) Before ¶
func (r *Router[T]) Before(before BeforeFunc[T])
func (*Router[T]) Delete ¶
func (r *Router[T]) Delete(path string, handler HandlerFunc[T])
Defines a new Route that responds to DELETE requests.
func (*Router[T]) Get ¶
func (r *Router[T]) Get(path string, handler HandlerFunc[T])
Defines a new Route that responds to GET requests.
func (*Router[T]) Match ¶
func (r *Router[T]) Match(method string, path string, handler HandlerFunc[T])
Match is used to add a new Route to the Router
func (*Router[T]) Missing ¶
func (r *Router[T]) Missing(handler HandlerFunc[T])
Defines a handler that is called when no route matches the request.
func (*Router[T]) Patch ¶
func (r *Router[T]) Patch(path string, handler HandlerFunc[T])
Defines a new Route that responds to PATCH requests.
func (*Router[T]) Post ¶
func (r *Router[T]) Post(path string, handler HandlerFunc[T])
Defines a new Route that responds to POST requests.
func (*Router[T]) Put ¶
func (r *Router[T]) Put(path string, handler HandlerFunc[T])
Defines a new Route that responds to PUT requests.
func (*Router[T]) ServeHTTP ¶
func (router *Router[T]) ServeHTTP(rw http.ResponseWriter, r *http.Request)
func (*Router[T]) Use ¶
func (r *Router[T]) Use(middleware Middleware)
Defines a new middleware that is called in each request before the matching route is called, if one exists. Middleware are only passed a router.BaseAction and not the application specific action. This is due to middleware being treated as a low-level API.
If you need access to the application specific action, you can use the actionCreator function passed to New or NewGroup.
Middleware is called in the order that they are added. Middleware must call next in order to continue the request, otherwise the request is halted.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
middleware
|
|
slashnormalizer
Package slashnormalizer provides a middleware that normalizes the URL path by removing duplicate slashes and redirects that normalized URL path.
|
Package slashnormalizer provides a middleware that normalizes the URL path by removing duplicate slashes and redirects that normalized URL path. |
The mlog package provides a simple structured logger.
|
The mlog package provides a simple structured logger. |