trout: darlinggo.co/trout Index | Examples | Files

package trout

import "darlinggo.co/trout"

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

Package Files

doc.go route.go trie.go

func RequestVars Uses

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.

Code:

postsHandler := http.HandlerFunc(
    func(w http.ResponseWriter, r *http.Request) {
        // RequestVars returns an http.Header object
        vars := trout.RequestVars(r)

        // you can use Get, but if a parameter name is
        // repeated, you'll only get the first instance
        // of it.
        firstID := vars.Get("id")

        // you can access all the instances of a parameter name
        // using the map index. Just remember to use
        // http.CanonicalHeaderKey.
        allIDs := vars[http.CanonicalHeaderKey("id")]
        secondID := allIDs[1]

        w.Write([]byte(fmt.Sprintf("%s\n%v\n%s",
            firstID, allIDs, secondID)))
    })

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

req, _ := http.NewRequest("GET", "http://example.com/posts/foo/comments/bar", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

Output:

foo
[foo bar]
bar

type Endpoint Uses

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 Uses

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.

Code:

// usually your handler is defined elsewhere
// here we're defining a dummy for demo purposes
postsHandler := http.HandlerFunc(
    func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("matched"))
    })

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

// all requests to /posts/FOO/comments/BAR will be routed to
// postsHandler

// normally this is done by passing router to http.ListenAndServe,
// or using http.Handle("/", router), but we don't want to run a
// server, we just want to call the router by hand right now
req, _ := http.NewRequest("GET",
    "http://example.com/posts/foo/comments/bar", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

// the handler responds to any HTTP method
req, _ = http.NewRequest("POST",
    "http://example.com/posts/foo/comments/bar", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

// routes that don't match return a 404
req, _ = http.NewRequest("GET", "http://example.com/posts/foo", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

req, _ = http.NewRequest("PUT", "http://example.com/users/bar", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

// endpoints don't match on prefix
req, _ = http.NewRequest("GET", "http://example.com/posts/foo/comments/bar/id/baz", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

Output:

matched
matched
404 Page Not Found
404 Page Not Found
404 Page Not Found

func (*Endpoint) Methods Uses

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 Uses

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 Uses

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.

Code:

// usually your handler is defined elsewhere
// here we're defining a dummy for demo purposes
postsHandler := http.HandlerFunc(
    func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("matched"))
    })

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

// only requests to /posts/FOO that are made with the GET or POST
// methods will be routed to postsHandler. Every other method will get
// a 405.

// normally this is done by passing router to http.ListenAndServe,
// or using http.Handle("/", router), but we don't want to run a
// server, we just want to call the router by hand right now
req, _ := http.NewRequest("GET", "http://example.com/posts/foo", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

req, _ = http.NewRequest("POST", "http://example.com/posts/foo", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

// this will return a 405
req, _ = http.NewRequest("PUT", "http://example.com/posts/foo", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

Output:

matched
matched
405 Method Not Allowed

type Prefix Uses

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 Uses

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.

Code:

// usually your handler is defined elsewhere
// here we're defining a dummy for demo purposes
postsHandler := http.HandlerFunc(
    func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("matched"))
    })

var router trout.Router
router.Prefix("/posts/{slug}").Handler(postsHandler)

// all requests that begin with /posts/FOO will be routed to
// postsHandler

// normally this is done by passing router to http.ListenAndServe,
// or using http.Handle("/", router), but we don't want to run a
// server, we just want to call the router by hand right now

// an exact match still works
req, _ := http.NewRequest("GET", "http://example.com/posts/foo", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

// but now anything using that prefix matches, too
req, _ = http.NewRequest("GET", "http://example.com/posts/foo/comments/bar", nil)
router.ServeHTTP(exampleResponseWriter{}, req)

Output:

matched
matched

func (*Prefix) Methods Uses

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 Uses

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 Uses

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 Uses

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 Uses

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 Uses

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.

Package trout imports 6 packages (graph) and is imported by 1 packages. Updated 2019-08-28. Refresh now. Tools for package owners.