README

Importing trout

import "darlinggo.co/trout"

About trout

trout is an opinionated router that is biased towards RESTful services. It does not rely on global, mutable state and has no dependencies. trout also goes out of its way to enable servers to correctly respond with an http.StatusMethodNotAllowed error instead of an http.StatusNotFound error when the endpoint can be matched but is not configured to respond to the HTTP method the request used. It also takes pains to make sure that OPTIONS requests can be fulfilled, by making the methods an endpoint is configured with available to the http.Handler. In general, the over-arching goals of trout are:

  • Be simple. Rely only on the standard library, and provide the barest possible functionality to get the job done.
  • Be transparent. Allow http.Handlers to get to information that will help them do their jobs.
  • Be intuitive. Value sane defaults and clear behaviours.

Docs can be found on GoDoc.org.

If you're using trout, we encourage you to join the trout mailing list, which will be our main mode of communication.

Using trout

Creating a router

Creating a router is straight-forward: the trout.Router type's zero value is an acceptable router with no endpoints. Adding endpoints is a matter of calling methods on the variable.

var router trout.Router
router.Endpoint("/posts/{slug}/comments/{id}").Handler(postsHandler)

That routemr will now match the URL /posts/WHATEVERYOUTYPE/comments/123. You can replace WHATEVERYOUTYPE and 123 with any string that doesn't contain a /. All requests matching this pattern will be handled by postsHandler.

The Endpoint method is basic: it accepts a string to match the URL against. Strings get broken down into resources; resources are split by the / character. Resources come in two flavours: static and dynamic. A static resource will match the resource text exactly; posts and comments in the example above are static resources. Dynamic resources are just placeholders; they match any text at all; WHATEVERYOUTYPE and 123 are dynamic resources in the example above.

The Endpoint method returns a trout.Endpoint, which can have an http.Handler associated with it by calling its Handler method, and passing the http.Handler you want to use as the handler for requests that match the endpoint.

Working with HTTP methods

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

The example above associates postsHandler with the /posts/{slug} endpoint, but only for requests made using the GET or POST HTTP method. All other requests will return an http.StatusMethodNotAllowed error. Any number of methods can be passed to the Methods... errr... method.

Working with variables

Now that a handler has been matched, we need to get the values that filled the dynamic resources placeholders in the URL. The trout.RequestVars helper function can be used to return the values the were used.

Variables in trout are passed as request headers. All the trout parameters are set as Trout-Param-RESOURCETEXT, where RESOURCETEXT is the text you entered between { and } in the endpoint. For example, /posts/{slug}/comments/{id} would have Trout-Param-Slug and Trout-Param-Id set in the request headers. trout.RequestVars(r) simply returns all headers that begin with Trout-Param-, and strip that prefix, returning an http.Header object. So calling trout.RequestVars(r) in our example would return an http.Header object with keys for Id and Slug.

In the event that the same text is reused as a dynamic resource in multiple parts of the endpoint, both values will still be available, because each key in an http.Header corresponds to a slice of values. For example, if the endpoint is /posts/{id}/comments/{id}, the http.Header returned from trout.RequestVars(r) will contain just a single Id key, and it would hold two values. The values will always be in the same order they were in in the URL.

Setting the 404 and 405 responses

By default, trout will respond with http.StatusNotFound when no endpoint can fulfill the request, and http.StatusMethodNotAllowed when none of the endpoints that can fulfill the request are configured to respond to the HTTP method used. These defaults will also write a default error message as the response body. Furthermore, for http.StatusMethodNotAllowed responses, the Allow header will be set on the response, containing the methods the endpoint is configured to respond to.

Sometimes, however, you want something besides these defaults. In that case, you can set the Handle404 property on your router to the http.Handler you want to use for requests where the endpoint can't be found, and Handle405 to the http.Handler you want to use for requests where an endpoint is matched, but isn't configured to respond to the HTTP method used.

Getting extra information

trout sets two extra request headers when routing:

  • Trout-Timer is set to the number of nanoseconds it took to route the request. This allows you to monitor how much of your response time is spent on routing.
  • Trout-Pattern is set to the endpoint text that the request matched, which makes it easier to determine which endpoint resulted in the handler being called. This is particularly useful when using placeholders, as the value will always be the same, no matter what text is placed in the placeholder. This makes it easier to monitor at an endpoint-granularity.

Understanding routing

There are times when multiple endpoints can be used to serve the same request. A simplified example would be /version and /{id} both being endpoints on a router. When a request is made to /version, which should be used?

Trout resolves this by trying to find the most specific route that can handle the request. Endpoints get a score based on how many placeholders exist in the endpoint, and how close to the beginning of the endpoint they are. The more placeholders an endpoint has, and the earlier in the endpoint they are, the lower the score is. The highest scoring endpoint serves the request.

Documentation

Overview

    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
    router.Endpoint("/posts/{slug}/comments/{id}").Handler(postsHandler)
    

    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`
    

    Index

    Constants

    This section is empty.

    Variables

    This section is empty.

    Functions

    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.

      Types

      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.