Documentation
¶
Overview ¶
Package sage provides support for developing HTTP routers by exporting a trie data structure that matches HTTP requests against a list of registered routes and returns a route value (typically http.Handler, or a variation of it) for the route that matches the URL and HTTP method.
Example ¶
package main import ( "context" "fmt" "net/http" "net/http/httptest" "net/url" "github.com/nahojer/sage" ) func main() { type Handler func(ctx context.Context, w http.ResponseWriter, r *http.Request) routes := sage.NewRoutesTrie[Handler]() routes.Add(http.MethodGet, "/ping/:pong", func(ctx context.Context, w http.ResponseWriter, r *http.Request) { pong := ctx.Value("pong").(string) w.WriteHeader(200) fmt.Fprint(w, pong) }) req := httptest.NewRequest(http.MethodGet, "http://localhost/ping/"+url.PathEscape("It's-a me, Mario!"), nil) w := httptest.NewRecorder() h, params, found := routes.Lookup(req) if !found { panic("never reached") } ctx := context.WithValue(req.Context(), "pong", params["pong"]) h(ctx, w, req) fmt.Printf("Status: %d\n", w.Code) fmt.Printf("Body: %q\n", w.Body.String()) }
Output: Status: 200 Body: "It's-a me, Mario!"
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type RoutesTrie ¶
type RoutesTrie[T any] struct { // ParamFunc reports whether given path segment is parameterized and returns // the name to give this parameter. The name will be the key into params // returned by Lookup. // // The default ParamFunc consideres a path segment a parameter if it is // prefixed with a colon (":"). The returned parameter name is the path // segment with all leading colons trimmed. ParamFunc func(pathSegment string) (name string, isParam bool) // contains filtered or unexported fields }
RoutesTrie is a trie data structure that stores route values of type T.
func NewRoutesTrie ¶
func NewRoutesTrie[T any]() *RoutesTrie[T]
NewRoutesTrie returns a new RoutesTrie.
func (*RoutesTrie[T]) Add ¶
func (rt *RoutesTrie[T]) Add(method, pattern string, value T)
Add inserts a route value to the trie at the location defined by given HTTP method and URL path pattern. Subsequent calls to Add with the same method and pattern overrides the route value.
Route patterns ending with three dots ("...") are considered prefix routes. If there are no matching routes for a HTTP request's URL path and method, but a part of the path matches a prefix route, the prefix value will be used.
Path parameters are specified by prefixing a path segment with a colon (":"). The parameter name is the value of the path segment with leading colons removed. This behaviour can be customized by overriding the ParamFunc of the RoutesTrie.