Back to

Package trout

Latest Go to latest

The highest tagged major version is v2.

Published: Jul 21, 2018 | License: BSD-3-Clause | Module:


Package trout provides an opinionated router that's implemented using a basic trie.

The router is opinionated and biased towards basic RESTful services. Its main constraint is that its URL templating is very basic and has no support for regular expressions, prefix matching, or anything other than a direct equality comparison, unlike many routing libraries.

The router is specifically designed to support users that want to return correct information with OPTIONS requests, so it enables users to retrieve a list of HTTP methods an Endpoint is configured to respond to. It will not return the methods an Endpoint is implicitly configured to respond to by associating a Handler with the Endpoint itself. These HTTP methods can be accessed through the Trout-Methods header that is injected into the http.Request object. Each method will be its own string in the slice.

The router is also specifically designed to differentiate between a 404 (Not Found) response and a 405 (Method Not Allowed) response. It will use the configured Handle404 http.Handler when no Endpoint is found that matches the http.Request's Path property. It will use the configured Handle405 http.Handler when an Endpoint is found for the http.Request's Path, but the http.Request's Method has no Handler associated with it. Setting a default http.Handler for the Endpoint will result in the Handle405 http.Handler never being used for that Endpoint.

To map an Endpoint to a http.Handler:

var router trout.Router

All requests that match that URL structure will be passed to the postsHandler, no matter what HTTP method they use.

To map specific Methods to a http.Handler:

var router trout.Router
router.Endpoint("/posts/{slug}").Methods("GET", "POST").Handler(postsHandler)

Only requests that match that URL structure will be passed to the postsHandler, and only if they use the GET or POST HTTP method.

To access the URL parameter values inside a request, use the RequestVars helper:

func handler(w http.ResponseWriter, r *http.Request) {
	vars := trout.RequestVars(r)

This will return an http.Header object containing the parameter values. They are passed into the http.Handler by injecting them into the http.Request's Header property, with the header key of "Trout-Params-{parameter}". The RequestVars helper is just a convenience function to strip the prefix. Parameters are always passed without the curly braces. Finally, if a parameter name is used multiple times in a single URL template, values will be stored in the slice in the order they appeared in the template:

// for the template /posts/{id}/comments/{id}
// filled with /posts/hello-world/comments/1
vars := trout.RequestVars(r)
fmt.Println(vars.Get("id")) // outputs `hello-world`
fmt.Println(vars[http.CanonicalHeaderKey("id")]) // outputs `["hello-world", "1"]`
fmt.Println(vars[http.CanonicalHeaderKey("id"})][1]) // outputs `1`


func RequestVars

func RequestVars(r *http.Request) http.Header

RequestVars returns easy-to-access mappings of parameters to values for URL templates. Any {parameter} in your URL template will be available in the returned Header as a slice of strings, one for each instance of the {parameter}. In the case of a parameter name being used more than once in the same URL template, the values will be in the slice in the order they appeared in the template.

Values can easily be accessed by using the .Get() method of the returned Header, though to access multiple values, they must be accessed through the map. All parameters use http.CanonicalHeaderKey for their formatting. When using .Get(), the parameter name will be transformed automatically. When utilising the Header as a map, the parameter name needs to have http.CanonicalHeaderKey applied manually.

type Endpoint

type Endpoint branch

Endpoint defines a single URL template that requests can be matched against. It uses URL parameters to accept variables in the URL structure and make them available to the Handlers associated with the Endpoint.

func (*Endpoint) Handler

func (e *Endpoint) Handler(h http.Handler)

Handler associates the passed http.Handler with the Endpoint. This http.Handler will be used for all requests, regardless of the HTTP method they are using, unless overridden by the Methods method. Endpoints without a http.Handler associated with them will not be considered matches for requests, unless the request was made using an HTTP method that the Endpoint has an http.Handler mapped to.

func (*Endpoint) Methods

func (e *Endpoint) Methods(m ...string) Methods

Methods returns a Methods object that will enable the mapping of the passed HTTP request methods to a Methods object. On its own, this function does not modify anything. It should, instead, be used as a friendly shorthand to get to the Methods.Handler method.

type Methods

type Methods struct {
	// contains filtered or unexported fields

Methods defines a pairing of an Endpoint to the HTTP request methods that should be mapped to specific http.Handlers. Its sole purpose is to enable the Methods.Handler method.

func (Methods) Handler

func (m Methods) Handler(h http.Handler)

Handler maps a Methods object to a specific http.Handler. This overrides the http.Handler associated with the Endpoint to only handle specific HTTP method(s).

type Router

type Router struct {
	Handle404 http.Handler
	Handle405 http.Handler
	// contains filtered or unexported fields

Router defines a set of Endpoints that map requests to the http.Handlers. The http.Handler assigned to Handle404, if set, will be called when no Endpoint matches the current request. The http.Handler assigned to Handle405, if set, will be called when an Endpoint matches the current request, but has no http.Handler set for the HTTP method that the request used. Should either of these properties be unset, a default http.Handler will be used.

The Router type is safe for use with empty values, but makes no attempt at concurrency-safety in adding Endpoints or in setting properties. It should also be noted that the adding Endpoints while simultaneously routing requests will lead to undefined and (almost certainly) undesirable behaviour. Routers are intended to be initialised with a set of Endpoints, and then start serving requests. Using them outside of this use case is unsupported.

func (*Router) Endpoint

func (router *Router) Endpoint(e string) *Endpoint

Endpoint defines a new Endpoint on the Router. The Endpoint should be a URL template, using curly braces to denote parameters that should be filled at runtime. For example, `{id}` denotes a parameter named `id` that should be filled with whatever the request has in that space.

Parameters are always `/`-separated strings. There is no support for regular expressions or other limitations on what may be in those strings. A parameter is simply defined as "whatever is between these two / characters".

func (Router) ServeHTTP

func (router Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP serves the request by matching it to a Handler.

func (*Router) SetPrefix

func (router *Router) SetPrefix(prefix string)

SetPrefix sets a string prefix for the Router that won't be taken into account when matching Endpoints. This is usually set to whatever path is associated with the http.Handler serving the Router.

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier