High-speed, flexible tree-based HTTP router for Go.

Overview

httptreemux Build Status GoDoc

High-speed, flexible, tree-based HTTP router for Go.

This is inspired by Julien Schmidt's httprouter, in that it uses a patricia tree, but the implementation is rather different. Specifically, the routing rules are relaxed so that a single path segment may be a wildcard in one route and a static token in another. This gives a nice combination of high performance with a lot of convenience in designing the routing patterns. In benchmarks, httptreemux is close to, but slightly slower than, httprouter.

Release notes may be found using the Github releases tab. Version numbers are compatible with the Semantic Versioning 2.0.0 convention, and a new release is made after every change to the code.

Installing with Go Modules

When using Go Modules, import this repository with import "github.com/dimfeld/httptreemux/v5" to ensure that you get the right version.

Why?

There are a lot of good routers out there. But looking at the ones that were really lightweight, I couldn't quite get something that fit with the route patterns I wanted. The code itself is simple enough, so I spent an evening writing this.

Handler

The handler is a simple function with the prototype func(w http.ResponseWriter, r *http.Request, params map[string]string). The params argument contains the parameters parsed from wildcards and catch-alls in the URL, as described below. This type is aliased as httptreemux.HandlerFunc.

Using http.HandlerFunc

Due to the inclusion of the context package as of Go 1.7, httptreemux now supports handlers of type http.HandlerFunc. There are two ways to enable this support.

Adapting an Existing Router

The UsingContext method will wrap the router or group in a new group at the same path, but adapted for use with context and http.HandlerFunc.

router := httptreemux.New()

group := router.NewGroup("/api")
group.GET("/v1/:id", func(w http.ResponseWriter, r *http.Request, params map[string]string) {
    id := params["id"]
    fmt.Fprintf(w, "GET /api/v1/%s", id)
})

// UsingContext returns a version of the router or group with context support.
ctxGroup := group.UsingContext() // sibling to 'group' node in tree
ctxGroup.GET("/v2/:id", func(w http.ResponseWriter, r *http.Request) {
    ctxData := httptreemux.ContextData(r.Context())
    params := ctxData.Params()
    id := params["id"]

    // Useful for middleware to see which route was hit without dealing with wildcards
    routePath := ctxData.Route()

    // Prints GET /api/v2/:id id=...
    fmt.Fprintf(w, "GET %s id=%s", routePath, id)
})

http.ListenAndServe(":8080", router)

New Router with Context Support

The NewContextMux function returns a router preconfigured for use with context and http.HandlerFunc.

router := httptreemux.NewContextMux()

router.GET("/:page", func(w http.ResponseWriter, r *http.Request) {
    params := httptreemux.ContextParams(r.Context())
    fmt.Fprintf(w, "GET /%s", params["page"])
})

group := router.NewGroup("/api")
group.GET("/v1/:id", func(w http.ResponseWriter, r *http.Request) {
    ctxData := httptreemux.ContextData(r.Context())
    params := ctxData.Params()
    id := params["id"]

    // Useful for middleware to see which route was hit without dealing with wildcards
    routePath := ctxData.Route()

    // Prints GET /api/v1/:id id=...
    fmt.Fprintf(w, "GET %s id=%s", routePath, id)
})

http.ListenAndServe(":8080", router)

Routing Rules

The syntax here is also modeled after httprouter. Each variable in a path may match on one segment only, except for an optional catch-all variable at the end of the URL.

Some examples of valid URL patterns are:

  • /post/all
  • /post/:postid
  • /post/:postid/page/:page
  • /post/:postid/:page
  • /images/*path
  • /favicon.ico
  • /:year/:month/
  • /:year/:month/:post
  • /:page

Note that all of the above URL patterns may exist concurrently in the router.

Path elements starting with : indicate a wildcard in the path. A wildcard will only match on a single path segment. That is, the pattern /post/:postid will match on /post/1 or /post/1/, but not /post/1/2.

A path element starting with * is a catch-all, whose value will be a string containing all text in the URL matched by the wildcards. For example, with a pattern of /images/*path and a requested URL images/abc/def, path would contain abc/def. A catch-all path will not match an empty string, so in this example a separate route would need to be installed if you also want to match /images/.

Using : and * in routing patterns

The characters : and * can be used at the beginning of a path segment by escaping them with a backslash. A double backslash at the beginning of a segment is interpreted as a single backslash. These escapes are only checked at the very beginning of a path segment; they are not necessary or processed elsewhere in a token.

router.GET("/foo/\\*starToken", handler) // matches /foo/*starToken
router.GET("/foo/star*inTheMiddle", handler) // matches /foo/star*inTheMiddle
router.GET("/foo/starBackslash\\*", handler) // matches /foo/starBackslash\*
router.GET("/foo/\\\\*backslashWithStar") // matches /foo/\*backslashWithStar

Routing Groups

Lets you create a new group of routes with a given path prefix. Makes it easier to create clusters of paths like:

  • /api/v1/foo
  • /api/v1/bar

To use this you do:

router = httptreemux.New()
api := router.NewGroup("/api/v1")
api.GET("/foo", fooHandler) // becomes /api/v1/foo
api.GET("/bar", barHandler) // becomes /api/v1/bar

Routing Priority

The priority rules in the router are simple.

  1. Static path segments take the highest priority. If a segment and its subtree are able to match the URL, that match is returned.
  2. Wildcards take second priority. For a particular wildcard to match, that wildcard and its subtree must match the URL.
  3. Finally, a catch-all rule will match when the earlier path segments have matched, and none of the static or wildcard conditions have matched. Catch-all rules must be at the end of a pattern.

So with the following patterns adapted from simpleblog, we'll see certain matches:

router = httptreemux.New()
router.GET("/:page", pageHandler)
router.GET("/:year/:month/:post", postHandler)
router.GET("/:year/:month", archiveHandler)
router.GET("/images/*path", staticHandler)
router.GET("/favicon.ico", staticHandler)

Example scenarios

  • /abc will match /:page
  • /2014/05 will match /:year/:month
  • /2014/05/really-great-blog-post will match /:year/:month/:post
  • /images/CoolImage.gif will match /images/*path
  • /images/2014/05/MayImage.jpg will also match /images/*path, with all the text after /images stored in the variable path.
  • /favicon.ico will match /favicon.ico

Special Method Behavior

If TreeMux.HeadCanUseGet is set to true, the router will call the GET handler for a pattern when a HEAD request is processed, if no HEAD handler has been added for that pattern. This behavior is enabled by default.

Go's http.ServeContent and related functions already handle the HEAD method correctly by sending only the header, so in most cases your handlers will not need any special cases for it.

By default TreeMux.OptionsHandler is a null handler that doesn't affect your routing. If you set the handler, it will be called on OPTIONS requests to a path already registered by another method. If you set a path specific handler by using router.OPTIONS, it will override the global Options Handler for that path.

Trailing Slashes

The router has special handling for paths with trailing slashes. If a pattern is added to the router with a trailing slash, any matches on that pattern without a trailing slash will be redirected to the version with the slash. If a pattern does not have a trailing slash, matches on that pattern with a trailing slash will be redirected to the version without.

The trailing slash flag is only stored once for a pattern. That is, if a pattern is added for a method with a trailing slash, all other methods for that pattern will also be considered to have a trailing slash, regardless of whether or not it is specified for those methods too. However this behavior can be turned off by setting TreeMux.RedirectTrailingSlash to false. By default it is set to true.

One exception to this rule is catch-all patterns. By default, trailing slash redirection is disabled on catch-all patterns, since the structure of the entire URL and the desired patterns can not be predicted. If trailing slash removal is desired on catch-all patterns, set TreeMux.RemoveCatchAllTrailingSlash to true.

router = httptreemux.New()
router.GET("/about", pageHandler)
router.GET("/posts/", postIndexHandler)
router.POST("/posts", postFormHandler)

GET /about will match normally.
GET /about/ will redirect to /about.
GET /posts will redirect to /posts/.
GET /posts/ will match normally.
POST /posts will redirect to /posts/, because the GET method used a trailing slash.

Custom Redirects

RedirectBehavior sets the behavior when the router redirects the request to the canonical version of the requested URL using RedirectTrailingSlash or RedirectClean. The default behavior is to return a 301 status, redirecting the browser to the version of the URL that matches the given pattern.

These are the values accepted for RedirectBehavior. You may also add these values to the RedirectMethodBehavior map to define custom per-method redirect behavior.

  • Redirect301 - HTTP 301 Moved Permanently; this is the default.
  • Redirect307 - HTTP/1.1 Temporary Redirect
  • Redirect308 - RFC7538 Permanent Redirect
  • UseHandler - Don't redirect to the canonical path. Just call the handler instead.

Rationale/Usage

On a POST request, most browsers that receive a 301 will submit a GET request to the redirected URL, meaning that any data will likely be lost. If you want to handle and avoid this behavior, you may use Redirect307, which causes most browsers to resubmit the request using the original method and request body.

Since 307 is supposed to be a temporary redirect, the new 308 status code has been proposed, which is treated the same, except it indicates correctly that the redirection is permanent. The big caveat here is that the RFC is relatively recent, and older or non-compliant browsers will not handle it. Therefore its use is not recommended unless you really know what you're doing.

Finally, the UseHandler value will simply call the handler function for the pattern, without redirecting to the canonical version of the URL.

RequestURI vs. URL.Path

Escaped Slashes

Go automatically processes escaped characters in a URL, converting + to a space and %XX to the corresponding character. This can present issues when the URL contains a %2f, which is unescaped to '/'. This isn't an issue for most applications, but it will prevent the router from correctly matching paths and wildcards.

For example, the pattern /post/:post would not match on /post/abc%2fdef, which is unescaped to /post/abc/def. The desired behavior is that it matches, and the post wildcard is set to abc/def.

Therefore, this router defaults to using the raw URL, stored in the Request.RequestURI variable. Matching wildcards and catch-alls are then unescaped, to give the desired behavior.

TL;DR: If a requested URL contains a %2f, this router will still do the right thing. Some Go HTTP routers may not due to Go issue 3659.

Escaped Characters

As mentioned above, characters in the URL are not unescaped when using RequestURI to determine the matched route. If this is a problem for you and you are unable to switch to URL.Path for the above reasons, you may set router.EscapeAddedRoutes to true. This option will run each added route through the URL.EscapedPath function, and add an additional route if the escaped version differs.

http Package Utility Functions

Although using RequestURI avoids the issue described above, certain utility functions such as http.StripPrefix modify URL.Path, and expect that the underlying router is using that field to make its decision. If you are using some of these functions, set the router's PathSource member to URLPath. This will give up the proper handling of escaped slashes described above, while allowing the router to work properly with these utility functions.

Concurrency

The router contains an RWMutex that arbitrates access to the tree. This allows routes to be safely added from multiple goroutines at once.

No concurrency controls are needed when only reading from the tree, so the default behavior is to not use the RWMutex when serving a request. This avoids a theoretical slowdown under high-usage scenarios from competing atomic integer operations inside the RWMutex. If your application adds routes to the router after it has begun serving requests, you should avoid potential race conditions by setting router.SafeAddRoutesWhileRunning to true to use the RWMutex when serving requests.

Error Handlers

NotFoundHandler

TreeMux.NotFoundHandler can be set to provide custom 404-error handling. The default implementation is Go's http.NotFound function.

MethodNotAllowedHandler

If a pattern matches, but the pattern does not have an associated handler for the requested method, the router calls the MethodNotAllowedHandler. The default version of this handler just writes the status code http.StatusMethodNotAllowed and sets the response header's Allowed field appropriately.

Panic Handling

TreeMux.PanicHandler can be set to provide custom panic handling. The SimplePanicHandler just writes the status code http.StatusInternalServerError. The function ShowErrorsPanicHandler, adapted from gocraft/web, will print panic errors to the browser in an easily-readable format.

Unexpected Differences from Other Routers

This router is intentionally light on features in the name of simplicity and performance. When coming from another router that does heavier processing behind the scenes, you may encounter some unexpected behavior. This list is by no means exhaustive, but covers some nonobvious cases that users have encountered.

gorilla/pat query string modifications

When matching on parameters in a route, the gorilla/pat router will modify Request.URL.RawQuery to make it appear like the parameters were in the query string. httptreemux does not do this. See Issue #26 for more details and a code snippet that can perform this transformation for you, should you want it.

httprouter and catch-all parameters

When using httprouter, a route with a catch-all parameter (e.g. /images/*path) will match on URLs like /images/ where the catch-all parameter is empty. This router does not match on empty catch-all parameters, but the behavior can be duplicated by adding a route without the catch-all (e.g. /images/).

Middleware

This package provides no middleware. But there are a lot of great options out there and it's pretty easy to write your own. The router provides the Use and UseHandler functions to ease the creation of middleware chains. (Real documentation of these functions coming soon.)

Acknowledgements

Comments
  • Example, or documentation, for integration of middleware(s)

    Example, or documentation, for integration of middleware(s)

    I'm considering to move to httptreemux, from go-gin. However, I'm missing middleware support. The basic use case is handling of authorization (extract information from request, validate, and set context parameters).

    The README says, that it's easy:

    This package provides no middleware. But there are a lot of great options out there and it's pretty easy to write your own.

    However, I have no clue, how to add any middleware to httptreemux. Can you please add any example, how to do that for some group of routes?

    opened by kravemir 13
  • URL escaped paths don't match

    URL escaped paths don't match

    Consider the following route:

    router.GET("/foo/\\*starToken", handler) // matches /foo/*starToken
    

    And the following client code:

    u := URL{Host: "localhost:8080", Scheme: "http", Path: "/foo/*starToken"}
    req, _ := http.NewRequest("GET", u.String(), nil)
    resp, _ := http.DefaultClient.Do(req)
    if resp.StatusCode == 404 {
        fmt.Println("oh noes")
    }
    

    Then "oh noes" gets printed. That's because u.String() returns:

    "http://localhost:8080/foo/%2AstarToken"
    

    It seems httptreemux is not handling the escape properly. Now it could also be argued that the stdlib is being a bit too generous in its escaping, http://www.rfc-editor.org/rfc/rfc1738.txt states that "*" is OK in URLs but it is what it is...

    opened by raphael 11
  • Method Not Allowed returned when it should not be.

    Method Not Allowed returned when it should not be.

    Consider the following code:

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    
        "github.com/dimfeld/httptreemux"
    )
    
    func main() {
        router := httptreemux.New()
        router.OPTIONS("/*cors", handler)
        router.GET("/foo/:id", handler)
        log.Fatal(http.ListenAndServe(":8080", router))
    }
    
    func handler(w http.ResponseWriter, r *http.Request, params map[string]string) {
        w.Write([]byte(fmt.Sprintf("%s OK", r.Method)))
    }
    

    Running the corresponding application and making requests to it produces:

    $ http localhost:8080/foo/2
    HTTP/1.1 200 OK
    Content-Length: 6
    Content-Type: text/plain; charset=utf-8
    Date: Mon, 14 Mar 2016 03:55:48 GMT
    
    GET OK
    

    Correct

    $ http options localhost:8080/foo
    HTTP/1.1 200 OK
    Content-Length: 10
    Content-Type: text/plain; charset=utf-8
    Date: Mon, 14 Mar 2016 03:55:57 GMT
    
    OPTIONS OK 
    

    Correct

    $ http options localhost:8080/foo/2
    HTTP/1.1 405 Method Not Allowed
    Allow: GET
    Content-Length: 0
    Content-Type: text/plain; charset=utf-8
    Date: Mon, 14 Mar 2016 03:55:54 GMT
    

    Incorrect

    opened by raphael 9
  • proposal: use http.HandlerFunc instead of the 2 custom handler funcs

    proposal: use http.HandlerFunc instead of the 2 custom handler funcs

    In go 1.7, the request has an extra context field. It can be used for storing the parameter map and the panic data, instead of using custom handler functions with an extra parameter.

    I've played around with the idea in this fork: https://github.com/urandom/httptreemux

    To me it seems a good usage of the context is to store the whole parameter map as a single key. That's because usually when people have url parameters, they want all of them, as opposed just one or two items. The retrieval is also faster, since the context is essentially a linked list. The panic handler is quite similar.

    I've added two functions in in the package, RequestParams and RequestError, though I'm not sure if the names are perfect.

    If you approve of this proposal, perhaps it would be best if you make these changes in a version 5 branch, so you can still have version 4 if you want to break the api in some other way for the go1.6 and lower.

    opened by urandom 8
  • Discrepancy in package interface

    Discrepancy in package interface

    Hello, I'm trying to leverage the ability to use the request context to retrieve the path parameters and I'm finding that the way to do it doesn't exactly work the way I would want it to. Sorry it's a bit of a long winded explanation but I can't think of a better way to go about it...

    • One may create a tree mux with New(). That object is a Group so exposes methods to register httptreemux handlers. It's also a http.Handler.
    • One may create a group using NewGroup. A group makes it possible to register httptreemux handlers.
    • One may create a context group with UsingContext which makes it possible to register http handlers.

    One cannot however create a tree mux which would both allow registering http handlers and expose a ServeHTTP method. At the end of the day that's the interface I wish to have:

    	Mux interface {
    		http.Handler
    		Handle(method, pattern string, handler http.HandlerFunc)
    	}
    

    This is what I need to do in order to achieve this:

    type mux struct {
    	r *httptreemux.TreeMux
    	g *httptreemux.ContextGroup
    }
    
    func NewMux() Mux {
    	r := httptreemux.New()
    	r.EscapeAddedRoutes = true
    	return &mux{r: r, g: r.UsingContext()}
    }
    
    func (m *mux) Handle(method, pattern string, handler http.HandlerFunc) {
    	m.g.Handle(method, pattern, handler)
    }
    
    func (m *mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    	m.r.ServeHTTP(w, r)
    }
    

    Really I wish I could just do httptreemux.NewWithContext() or something like that which would return an object that exposes both Handle (accepting http.HandlerFunc) and ServeHTTP.

    Hope that makes sense....

    opened by raphael 7
  • Usage with negroni and route groups

    Usage with negroni and route groups

    Hey, thanks for the awesome router!

    I struggling with creating two different groups of routes with group-specific middleware. Currently I'm using negroni as a middleware helper and what I want to achieve is for example to have:

    /users
    /events
    ...
    

    and the rest of my REST api to be protected by an API-Key HTTP Header middleware and:

    /web/doThis
    /web/doThat
    

    to be protected by a second API-Key HTTP Header middleware.

    Currently I came up with the following code (based on the proposal in the negroni documentation https://github.com/codegangsta/negroni#route-specific-middleware) but it doesn't work because httptreemux is not accepting negroni.New() as a handler.

    mux := httptreemux.New()
    webmux := httptreemux.New()
    
    n := negroni.Classic()
    n.Use(gzip.Gzip(gzip.DefaultCompression))
    n.Use(negroni.HandlerFunc(handler.ApiKey))
    
    api.NewApi(mux, webmux).Init() // where routes get defined
    
    // based on negroni documentation
    mux.Handle("GET", "/web", negroni.New(      // not even sure if GET makes sense for all
        negroni.HandlerFunc(handler.ApiKeyWeb),
        negroni.Wrap(webmux),
    ))
    
    n.UseHandler(mux)
    n.Run(":8080")
    

    Can you think of a way to make this work out? You can tell that I'm pretty new to middlewares gg

    Any help, or tip or direction is very appreciated :)

    regards

    opened by codepushr 7
  • Update to use PathUnescape on path params

    Update to use PathUnescape on path params

    QueryUnescape handles escaping differently than PathUnescape. Here is a playground example https://play.golang.org/p/oCCzMI102E

    Do you have any concerns about changing to use PathUnescape here?

    opened by itchy 6
  • OAuth package goth does not work

    OAuth package goth does not work

    Apparently query parameters which should be available via req.URL.Query().Get("some-key") get removed by httptreemux. Not that this is necessarily a bug, but if this is by design, one should be aware of that.

    opened by dc0d 6
  • Feature/case insensitive routing

    Feature/case insensitive routing

    • Added case insensitive routing support
    • Updated tests
    • Updated documentation

    Related to: https://github.com/dimfeld/httptreemux/issues/83#issue-1006706239

    opened by Russman12 5
  • Add ability to map root of subgroup

    Add ability to map root of subgroup

    There was a bug in the initial implementation of subgroups where mapping the root of a subgroup ended up in adding the "add trailing slash" logic.

    This code basically changes it so if you do subGroup.Handle("/",...) then we just use the subgroups original path.

    This change maps: router.NewGroup("/foo").GET("/") -> /foo (no trailing slash added)

    before this change it did: /foo (with add trailing slash enabled)

    opened by dbudworth 5
  • httptreemux is incompatible with httptest.ResponseRecorder testing style

    httptreemux is incompatible with httptest.ResponseRecorder testing style

    Running the following snippet gives a panic:

    package main
    
    import (
        "net/http"
        "net/http/httptest"
    
        "github.com/dimfeld/httptreemux"
    )
    
    func main() {
        req, _ := http.NewRequest("GET", "http://localhost/", nil)
    
        rtr := httptreemux.New()
        rtr.GET("/", func(_ http.ResponseWriter, _ *http.Request, _ map[string]string) {})
    
        respRec := httptest.NewRecorder()
        rtr.ServeHTTP(respRec, req)
    }
    
    panic: runtime error: index out of range
    
    goroutine 1 [running]:
    github.com/dimfeld/httptreemux.(*TreeMux).ServeHTTP(0xc2080680c0, 0x567f68, 0xc20801e0c0, 0xc208050b60)
        /.../github.com/dimfeld/httptreemux/router.go:170 +0x6ff
    main.main()
        /.../test.go:21 +0x3ee
    exit status 2
    

    The reason is that httptreemux uses request.RequestURI which is not set for "client" requests.

    opened by StephanDollberg 5
  • Question: will regexp routes be considered?

    Question: will regexp routes be considered?

    Just a question, does regexp routes will be supported? Or if it's welcomed to accept PR to support regexp? Sometimes it's quite useful doing some migration work.

    opened by jxskiss 2
  • Remove routes

    Remove routes

    Since we can now add routes at runtime (using the mutex), I think it would be appropriate to provide a function to remove routes as well.

    Please excuse me if there is such a function already. I couldn't find anything.

    opened by kabukky 5
Releases(v5.4.0)
  • v5.4.0(Oct 7, 2021)

  • v5.3.0(Mar 30, 2021)

  • v5.2.2(Apr 24, 2020)

  • v5.2.1(Apr 17, 2020)

    The internal contextData type now uses a pointer receiver to avoid copying it on every access. Also added a ContextRoute helper method to directly extract the Route string if that's all you need. Thanks again to @stuartclan for the help!

    Source code(tar.gz)
    Source code(zip)
  • v5.2.0(Apr 16, 2020)

    This is mostly to allow logging middleware to show the actual route matched without expanded wildcards.

    Request context data can now be accessed using httptreemux.ContextData(r.Context()), which returns an interface ContextRouteData containing the parameters and the route path. The old ContextParams method is no longer recommended, but will continue to exist and work as before.

    Thanks to @stuartclan for the suggestion and help with the implementation and review!

    Source code(tar.gz)
    Source code(zip)
  • v5.1.0(Apr 11, 2020)

    Middleware is now officially supported. Documentation coming soon. Many thanks to @vmihailenco for the PR and @kravemir for help with the review!

    Source code(tar.gz)
    Source code(zip)
  • v5.0.2(Dec 18, 2018)

  • v5.0.1(Feb 13, 2018)

    When redirecting from a URL like /The%20Path/, the URL was incorrectly escaped again, redirecting to /The%2520Path.

    Thanks to @Backfighter for the detailed bug report!

    Source code(tar.gz)
    Source code(zip)
  • v5.0.0(Oct 11, 2017)

    Go 1.7 and below continues to use UrlUnescape. I bumped the major version since this is a breaking change, but I doubt anyone will complain.

    Source code(tar.gz)
    Source code(zip)
  • v4.1.0(Oct 2, 2017)

    This function assists package clients in writing unit tests. It simply adds the given params map into a Context object at the internal params key.

    Source code(tar.gz)
    Source code(zip)
  • v4.0.1(Aug 2, 2017)

    MethodNotAllowedHandler can access the handler map to generate the list of allowed methods, so it needs a read lock around it when new routes are being added during runtime. Operation without SafeAddRoutesWhileRunning was not affected by this bug.

    Source code(tar.gz)
    Source code(zip)
  • v4.0.0(Jun 21, 2017)

    #52 had a need to be able to see if a route exists in the router, without necessarily serving it or responding with an error when it doesn't exist. This release adds that functionality.

    The breaking change is from #50, which changes ParamContextKey, used for fetching a Request Context's parameters from an exported string, to an unexported variable/type. You should have been using the ContextParams function instead of this variable anyway, so it is unlikely that any changes will be required. Thanks to @bontibon for suggesting this change.

    Source code(tar.gz)
    Source code(zip)
  • v3.9.0(May 31, 2017)

  • v3.8.0(Feb 26, 2017)

    TheNewContextMux function can be used to create a TreeMux preconfigured for use with http.HandlerFunc and context. The main difference here is that this object can be used as an http.Handler as well, unlike groups created from a TreeMux with UsingContext.

    Source code(tar.gz)
    Source code(zip)
  • v3.7.0(Dec 31, 2016)

    Set TreeMux.SafeAddRoutesWhileRunning to true to use the feature. It is optional because most people don't use the router this way, and there is a theoretical performance loss at high usage around RWMutex.RLock even when no writers are involved.

    Source code(tar.gz)
    Source code(zip)
  • v3.6.0(Dec 20, 2016)

    The trie now uses a mutex to allow safe, concurrent route additions from multiple goroutines. The mutex is only used on the write path, which means that it is still unsafe to add routes once the router is in use by an HTTP server.

    Additionally, the code from github.com/dimfeld/httppath has been integrated directly into this repository.

    Thanks to @bastiankoetsier for these two PRs!

    Source code(tar.gz)
    Source code(zip)
  • v3.5.1(Oct 17, 2016)

    This was an internal function not meant for use by clients of the library. Not bumping the major version since the function was just added yesterday and I'm almost 100% sure that nobody was relying on it.

    Source code(tar.gz)
    Source code(zip)
  • v3.5.0(Oct 16, 2016)

  • v3.4.0(Oct 5, 2016)

  • v3.3.0(Sep 14, 2016)

    The wildcard token parser now uses strings.IndexByte instead of a for loop when finding the next slash. The implementation of IndexByte in previous versions of Go was slow on short strings, but this has been corrected in Go 1.7.

    Performance is pretty much unchanged for short tokens, and a few percent faster for long tokens.

    Source code(tar.gz)
    Source code(zip)
  • v3.2.0(Sep 13, 2016)

    With Go 1.7+, there is now the option to store the parameters map inside Request.Context and use Go's standard http.HandlerFunc type for your handler functions. When doing this, theparams map may be accessed using the httptreemux.ContextParams(ctx) function.

    The original handler type, with params as an argument to the handler function, is still the default, so all existing code will continue working without changes. To use the new mode, the UsingContext() function will return a version of the mux set up to use the new handler style.

    Many thanks to @patrickrand for making this happen!

    Source code(tar.gz)
    Source code(zip)
  • v3.1.0(Aug 4, 2016)

    This can be useful when you need to support escaped characters and switching to URL.Path is not an option. Set router.EscapeAddedRoutes to true to use this.

    As of this version, releases will be prefixed with 'v' for proper semver compatibility.

    Source code(tar.gz)
    Source code(zip)
  • 3.0.0(Mar 31, 2016)

    The router now allows path segments containing asterisks and colons that are not wildcards. A * or : at the beginning of a path segment must be backslash escaped, like so: router.GET("\\*asteriskpath", handler). The backslash should not be included if it occurs anywhere else in the path, e.g. router.GET("aaa*bbb", handler) as it only checks at the beginning.

    Breaking Changes

    • The router no longer panics if you add a path segment containing : or * in the middle of the segment.
    • Path segments starting with two backslashes will be unescaped to start with a single backslash. That is, router.GET("\\\\abc") should now be router.GET("\\\\\\abc").
    Source code(tar.gz)
    Source code(zip)
  • 2.0.0(Mar 19, 2016)

    When a node is found but it does not handle the requested HTTP method, look for a less specific match in the rest of the tree that does handle that method.

    This also changes the behavior of HeadCanUseGet, which is now checked at route add time instead of at request time. This means that if you are setting HeadCanUseGet to false, you must do so before adding your routes.

    Due to the above change, the default MethodNotAllowed handler now includes HEAD in the list of allowed methods, as it should have all along.

    Both of these are breaking changes compared to the previous release, but in most cases existing code should not need to change to accommodate them.

    Source code(tar.gz)
    Source code(zip)
  • 1.4.2(Feb 9, 2016)

    This ensures that subgroups function as expected, rather than mashing together path components that are supposed to be separate. Thanks again to @dbudworth!

    Source code(tar.gz)
    Source code(zip)
  • 1.4.1(Feb 7, 2016)

    No change in functionality, just cleaner code layout by putting a default Group into the TreeMux object. Thanks to @bontibon for submitting this!

    Source code(tar.gz)
    Source code(zip)
  • 1.4.0(Dec 27, 2015)

    This creates an object that looks like the router object, but prefixes a given path to all paths passed to it. Thanks to @dbudworth for submitting this PR!

    Source code(tar.gz)
    Source code(zip)
  • 1.3.0(Dec 8, 2015)

Owner
Daniel Imfeld
CTO at Carevoyance, where I develop new ways to analyze and visualize relationships in medical data.
Daniel Imfeld
FastRouter is a fast, flexible HTTP router written in Go.

FastRouter FastRouter is a fast, flexible HTTP router written in Go. FastRouter contains some customizable options, such as TrailingSlashesPolicy, Pan

Razon Yang 21 Apr 19, 2022
Fast and flexible HTTP router

treemux - fast and flexible HTTP router Basic example Debug logging CORS example Error handling Rate limiting using Redis Gzip compression OpenTelemet

Vladimir Mihailenco 482 Sep 26, 2022
A high performance HTTP request router that scales well

HttpRouter HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or just mux for short) for Go. In contrast to the

Julien Schmidt 14.5k Sep 27, 2022
:tongue: CleverGo is a lightweight, feature rich and high performance HTTP router for Go.

CleverGo CleverGo is a lightweight, feature rich and trie based high performance HTTP request router. go get -u clevergo.tech/clevergo English 简体中文 Fe

CleverGo Web Framework 252 Sep 14, 2022
A high performance HTTP request router that scales well

HttpRouter HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or just mux for short) for Go. In contrast to the

Julien Schmidt 13.5k Dec 9, 2021
Bxog is a simple and fast HTTP router for Go (HTTP request multiplexer).

Bxog is a simple and fast HTTP router for Go (HTTP request multiplexer). Usage An example of using the multiplexer: package main import ( "io" "net

Eduard 103 Sep 7, 2022
A high performance fasthttp request router that scales well

FastHttpRouter FastHttpRouter is forked from httprouter which is a lightweight high performance HTTP request router (also called multiplexer or just m

招牌疯子 869 Sep 1, 2022
Simple Golang HTTP router

Bellt Simple Golang HTTP router Bellt Package implements a request router with the aim of managing controller actions based on fixed and parameterized

Guilherme Caruso 54 Jul 18, 2022
Go Server/API micro framework, HTTP request router, multiplexer, mux

?? gorouter Go Server/API micro framework, HTTP request router, multiplexer, mux. ?? ABOUT Contributors: Rafał Lorenz Want to contribute ? Feel free t

Rafał Lorenz 133 Sep 11, 2022
:rotating_light: Is a lightweight, fast and extensible zero allocation HTTP router for Go used to create customizable frameworks.

LARS LARS is a fast radix-tree based, zero allocation, HTTP router for Go. view examples. If looking for a more pure Go solution, be sure to check out

Go Playgound 389 Jul 27, 2022
A powerful HTTP router and URL matcher for building Go web servers with 🦍

gorilla/mux https://www.gorillatoolkit.org/pkg/mux Package gorilla/mux implements a request router and dispatcher for matching incoming requests to th

Gorilla Web Toolkit 17.4k Sep 25, 2022
An extremely fast Go (golang) HTTP router that supports regular expression route matching. Comes with full support for building RESTful APIs.

ozzo-routing You may consider using go-rest-api to jumpstart your new RESTful applications with ozzo-routing. Description ozzo-routing is a Go package

Ozzo Framework 440 Sep 14, 2022
Go HTTP router

violetear Go HTTP router http://violetear.org Design Goals Keep it simple and small, avoiding extra complexity at all cost. KISS Support for static an

Nicolas Embriz 104 Aug 13, 2022
xujiajun/gorouter is a simple and fast HTTP router for Go. It is easy to build RESTful APIs and your web framework.

gorouter xujiajun/gorouter is a simple and fast HTTP router for Go. It is easy to build RESTful APIs and your web framework. Motivation I wanted a sim

徐佳军 527 Sep 10, 2022
lightweight, idiomatic and composable router for building Go HTTP services

chi is a lightweight, idiomatic and composable router for building Go HTTP services. It's especially good at helping you write large REST API services

go-chi 12.2k Sep 18, 2022
Fast, simple, and lightweight HTTP router for Golang

Sariaf Fast, simple and lightweight HTTP router for golang Install go get -u github.com/majidsajadi/sariaf Features Lightweight compatible with net/ht

defectivepixel 33 Aug 19, 2022
Simple router build on `net/http` supports custom middleWare.

XMUS-ROUTER Fast lightweight router build on net/http supports delegate and in url params. usage : Create new router using NewRouter() which need rout

amupxm [amir hossein mokarrami far] 5 Dec 27, 2021
Simple HTTP router for Go

ngamux Simple HTTP router for Go Installation Examples Todo Installation Run this command with correctly configured Go toolchain. go get github.com/ng

null 52 Sep 27, 2022
Lightweight Router for Golang using net/http standard library with custom route parsing, handler and context.

Go-Lightweight-Router Lightweight Router for Golang using net/http standard library with custom route parsing, handler and context. Further developmen

null 0 Nov 3, 2021