README

Importing trout

import "darlinggo.co/trout/v2"

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 reasonable defaults and clear behaviours.

Docs can be found on GoDoc.org.

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 router 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 path elements; path elements are split by the / character. Path elements come in two flavours: static and dynamic. A static path element will match the path element text exactly; posts and comments in the example above are static path elements. Dynamic path elements 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 method.

Working with variables

Now that a handler has been matched, we need to get the values that filled the dynamic path element 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) 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.

Expand ▾ Collapse ▴

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 or anything other than a direct equality comparison or prefix match, 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 or Prefix is configured to respond to. It will not return the methods an Endpoint or Prefix is implicitly configured to respond to by associating a Handler with the Endpoint or Prefix 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 or Prefix is found that matches the http.Request's Path property. It will use the configured Handle405 http.Handler when an Endpoint or Prefix 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 or Prefix will result in the Handle405 http.Handler never being used for that Endpoint.

    Index

    Examples

    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.

      Example
      Output:
      
      foo
      [foo bar]
      bar
      

      Types

      type Endpoint

      type Endpoint node

        Endpoint defines a single URL template that requests can be matched against. It is only valid to instantiate an Endpoint by calling `Router.Endpoint`. Endpoints, on their own, are only useful for calling their methods, as they don't do anything until an http.Handler is associated with them.

        func (*Endpoint) Handler

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

          Handler sets the default http.Handler for `e`, to be used for all requests that `e` matches that don't match a method explicitly set for `e` using the Methods method.

          Handler is not concurrency-safe, and should not be used while the Router `e` belongs to is actively routing traffic.

          Example
          Output:
          
          matched
          matched
          404 Page Not Found
          404 Page Not Found
          404 Page Not Found
          

          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 the Endpoint. 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 HTTP request methods, to map designate specific http.Handlers for requests matching that Endpoint made using the specified methods. It is only valid to instantiate Methods by calling `Endpoint.Methods`. Methods, on their own, are only useful for calling the `Methods.Handler` method, as they don't modify the Router until their `Methods.Handler` method is called.

              func (Methods) Handler

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

                Handler associates an http.Handler with the Endpoint associated with `m`, to be used whenever a request that matches the Endpoint also matches one of the Methods associated with `m`.

                Handler is not concurrency-safe. It should not be called while the Router that owns the Endpoint that `m` belongs to is actively serving traffic.

                Example
                Output:
                
                matched
                matched
                405 Method Not Allowed
                

                type Prefix

                type Prefix node

                  Prefix defines a URL template that requests can be matched against. It is only valid to instantiate a prefix by calling `Router.Prefix`. Prefixes, on their own, are only useful for calling their methods, as they don't do anything until an http.Handler is associated with them.

                  Unlike Endpoints, Prefixes will match any request that starts with their prefix, no matter whether or not the request is for a URL that is longer than the Prefix.

                  func (*Prefix) Handler

                  func (p *Prefix) Handler(h http.Handler)

                    Handler sets the default http.Handler for `p`, to be used for all requests that `p` matches that don't match a method explicitly set for `p` using the Methods method.

                    Handler is not concurrency-safe, and should not be used while the Router `p` belongs to is actively routing traffic.

                    Example
                    Output:
                    
                    matched
                    matched
                    

                    func (*Prefix) Methods

                    func (p *Prefix) Methods(m ...string) Methods

                      Methods returns a Methods object that will enable the mapping of the passed HTTP request methods to the Prefix. 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 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".

                          Endpoints are always case-insensitive and coerced to lowercase. Endpoints will only match requests with URLs that match the entire Endpoint and have no extra path elements.

                          func (*Router) Prefix

                          func (router *Router) Prefix(p string) *Prefix

                            Prefix defines a new Prefix on the Router. The Prefix 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".

                            Prefixes are always case-insensitive and coerced to lowercase. Prefixes will only match requests with URLs that match the entire Prefix, but the URL may have additional path elements after the Prefix and still be considered a match.

                            func (Router) ServeHTTP

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

                              ServeHTTP finds the best handler for the request, using the 404 or 405 handlers if necessary, and serves the request.

                              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 whenever the Router is not passed directly to http.ListenAndServe, and is sent through some sort of muxer first. It should be set to whatever string the muxer is using when passing requests to the Router.

                                This function is not concurrency-safe; it should not be used while the Router is actively serving requests.