A high performance HTTP request router that scales well

Overview

HttpRouter Build Status Coverage Status GoDoc

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

In contrast to the default mux of Go's net/http package, this router supports variables in the routing pattern and matches against the request method. It also scales better.

The router is optimized for high performance and a small memory footprint. It scales well even with very long paths and a large number of routes. A compressing dynamic trie (radix tree) structure is used for efficient matching.

Features

Only explicit matches: With other routers, like http.ServeMux, a requested URL path could match multiple patterns. Therefore they have some awkward pattern priority rules, like longest match or first registered, first matched. By design of this router, a request can only match exactly one or no route. As a result, there are also no unintended matches, which makes it great for SEO and improves the user experience.

Stop caring about trailing slashes: Choose the URL style you like, the router automatically redirects the client if a trailing slash is missing or if there is one extra. Of course it only does so, if the new path has a handler. If you don't like it, you can turn off this behavior.

Path auto-correction: Besides detecting the missing or additional trailing slash at no extra cost, the router can also fix wrong cases and remove superfluous path elements (like ../ or //). Is CAPTAIN CAPS LOCK one of your users? HttpRouter can help him by making a case-insensitive look-up and redirecting him to the correct URL.

Parameters in your routing pattern: Stop parsing the requested URL path, just give the path segment a name and the router delivers the dynamic value to you. Because of the design of the router, path parameters are very cheap.

Zero Garbage: The matching and dispatching process generates zero bytes of garbage. The only heap allocations that are made are building the slice of the key-value pairs for path parameters, and building new context and request objects (the latter only in the standard Handler/HandlerFunc API). In the 3-argument API, if the request path contains no parameters not a single heap allocation is necessary.

Best Performance: Benchmarks speak for themselves. See below for technical details of the implementation.

No more server crashes: You can set a Panic handler to deal with panics occurring during handling a HTTP request. The router then recovers and lets the PanicHandler log what happened and deliver a nice error page.

Perfect for APIs: The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has built-in native support for OPTIONS requests and 405 Method Not Allowed replies.

Of course you can also set custom NotFound and MethodNotAllowed handlers and serve static files.

Usage

This is just a quick introduction, view the GoDoc for details.

Let's start with a trivial example:

package main

import (
    "fmt"
    "net/http"
    "log"

    "github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
    fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
    router := httprouter.New()
    router.GET("/", Index)
    router.GET("/hello/:name", Hello)

    log.Fatal(http.ListenAndServe(":8080", router))
}

Named parameters

As you can see, :name is a named parameter. The values are accessible via httprouter.Params, which is just a slice of httprouter.Params. You can get the value of a parameter either by its index in the slice, or by using the ByName(name) method: :name can be retrieved by ByName("name").

When using a http.Handler (using router.Handler or http.HandlerFunc) instead of HttpRouter's handle API using a 3rd function parameter, the named parameters are stored in the request.Context. See more below under Why doesn't this work with http.Handler?.

Named parameters only match a single path segment:

Pattern: /user/:user

 /user/gordon              match
 /user/you                 match
 /user/gordon/profile      no match
 /user/                    no match

Note: Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns /user/new and /user/:user for the same request method at the same time. The routing of different request methods is independent from each other.

Catch-All parameters

The second type are catch-all parameters and have the form *name. Like the name suggests, they match everything. Therefore they must always be at the end of the pattern:

Pattern: /src/*filepath

 /src/                     match
 /src/somefile.go          match
 /src/subdir/somefile.go   match

How does it work?

The router relies on a tree structure which makes heavy use of common prefixes, it is basically a compact prefix tree (or just Radix tree). Nodes with a common prefix also share a common parent. Here is a short example what the routing tree for the GET request method could look like:

Priority   Path             Handle
9          \                *<1>
3          ├s               nil
2          |├earch\         *<2>
1          |└upport\        *<3>
2          ├blog\           *<4>
1          |    └:post      nil
1          |         └\     *<5>
2          ├about-us\       *<6>
1          |        └team\  *<7>
1          └contact\        *<8>

Every *<num> represents the memory address of a handler function (a pointer). If you follow a path trough the tree from the root to the leaf, you get the complete route path, e.g \blog\:post\, where :post is just a placeholder (parameter) for an actual post name. Unlike hash-maps, a tree structure also allows us to use dynamic parts like the :post parameter, since we actually match against the routing patterns instead of just comparing hashes. As benchmarks show, this works very well and efficient.

Since URL paths have a hierarchical structure and make use only of a limited set of characters (byte values), it is very likely that there are a lot of common prefixes. This allows us to easily reduce the routing into ever smaller problems. Moreover the router manages a separate tree for every request method. For one thing it is more space efficient than holding a method->handle map in every single node, it also allows us to greatly reduce the routing problem before even starting the look-up in the prefix-tree.

For even better scalability, the child nodes on each tree level are ordered by priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:

  1. Nodes which are part of the most routing paths are evaluated first. This helps to make as much routes as possible to be reachable as fast as possible.
  2. It is some sort of cost compensation. The longest reachable path (highest cost) can always be evaluated first. The following scheme visualizes the tree structure. Nodes are evaluated from top to bottom and from left to right.
├------------
├---------
├-----
├----
├--
├--
└-

Why doesn't this work with http.Handler?

It does! The router itself implements the http.Handler interface. Moreover the router provides convenient adapters for http.Handlers and http.HandlerFuncs which allows them to be used as a httprouter.Handle when registering a route.

Named parameters can be accessed request.Context:

func Hello(w http.ResponseWriter, r *http.Request) {
    params := httprouter.ParamsFromContext(r.Context())

    fmt.Fprintf(w, "hello, %s!\n", params.ByName("name"))
}

Alternatively, one can also use params := r.Context().Value(httprouter.ParamsKey) instead of the helper function.

Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.

Automatic OPTIONS responses and CORS

One might wish to modify automatic responses to OPTIONS requests, e.g. to support CORS preflight requests or to set other headers. This can be achieved using the Router.GlobalOPTIONS handler:

router.GlobalOPTIONS = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    if r.Header.Get("Access-Control-Request-Method") != "" {
        // Set CORS headers
        header := w.Header()
        header.Set("Access-Control-Allow-Methods", header.Get("Allow"))
        header.Set("Access-Control-Allow-Origin", "*")
    }

    // Adjust status code to 204
    w.WriteHeader(http.StatusNoContent)
})

Where can I find Middleware X?

This package just provides a very efficient request router with a few extra features. The router is just a http.Handler, you can chain any http.Handler compatible middleware before the router, for example the Gorilla handlers. Or you could just write your own, it's very easy!

Alternatively, you could try a web framework based on HttpRouter.

Multi-domain / Sub-domains

Here is a quick example: Does your server serve multiple domains / hosts? You want to use sub-domains? Define a router per host!

// We need an object that implements the http.Handler interface.
// Therefore we need a type for which we implement the ServeHTTP method.
// We just use a map here, in which we map host names (with port) to http.Handlers
type HostSwitch map[string]http.Handler

// Implement the ServeHTTP method on our new type
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Check if a http.Handler is registered for the given host.
	// If yes, use it to handle the request.
	if handler := hs[r.Host]; handler != nil {
		handler.ServeHTTP(w, r)
	} else {
		// Handle host names for which no handler is registered
		http.Error(w, "Forbidden", 403) // Or Redirect?
	}
}

func main() {
	// Initialize a router as usual
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	// Make a new HostSwitch and insert the router (our http handler)
	// for example.com and port 12345
	hs := make(HostSwitch)
	hs["example.com:12345"] = router

	// Use the HostSwitch to listen and serve on port 12345
	log.Fatal(http.ListenAndServe(":12345", hs))
}

Basic Authentication

Another quick example: Basic Authentication (RFC 2617) for handles:

package main

import (
	"fmt"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"
)

func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		// Get the Basic Authentication credentials
		user, password, hasAuth := r.BasicAuth()

		if hasAuth && user == requiredUser && password == requiredPassword {
			// Delegate request to the given handle
			h(w, r, ps)
		} else {
			// Request Basic Authentication otherwise
			w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
		}
	}
}

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprint(w, "Not protected!\n")
}

func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprint(w, "Protected!\n")
}

func main() {
	user := "gordon"
	pass := "secret!"

	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/protected/", BasicAuth(Protected, user, pass))

	log.Fatal(http.ListenAndServe(":8080", router))
}

Chaining with the NotFound handler

NOTE: It might be required to set Router.HandleMethodNotAllowed to false to avoid problems.

You can use another http.Handler, for example another router, to handle requests which could not be matched by this router by using the Router.NotFound handler. This allows chaining.

Static files

The NotFound handler can for example be used to serve static files from the root path / (like an index.html file along with other assets):

// Serve static files from the ./public directory
router.NotFound = http.FileServer(http.Dir("public"))

But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like /static/*filepath or /files/*filepath.

Web Frameworks based on HttpRouter

If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:

  • Ace: Blazing fast Go Web Framework
  • api2go: A JSON API Implementation for Go
  • Gin: Features a martini-like API with much better performance
  • Goat: A minimalistic REST API server in Go
  • goMiddlewareChain: An express.js-like-middleware-chain
  • Hikaru: Supports standalone and Google AppEngine
  • Hitch: Hitch ties httprouter, httpcontext, and middleware up in a bow
  • httpway: Simple middleware extension with context for httprouter and a server with gracefully shutdown support
  • kami: A tiny web framework using x/net/context
  • Medeina: Inspired by Ruby's Roda and Cuba
  • Neko: A lightweight web application framework for Golang
  • pbgo: pbgo is a mini RPC/REST framework based on Protobuf
  • River: River is a simple and lightweight REST server
  • siesta: Composable HTTP handlers with contexts
  • xmux: xmux is a httprouter fork on top of xhandler (net/context aware)
Issues
  • Params via Go 1.7 Contexts

    Params via Go 1.7 Contexts

    With request-scoped contexts coming to net/http in go 1.7 there's no need for Handler and HandlerFunc to continue throwing away Params.

    It may be a little early for this change, but I wanted to get your eyes on it and start the discussion.

    feature 
    opened by teepark 26
  • License violation

    License violation

    @julienschmidt if you take closer look https://github.com/kataras/iris/blob/master/http.go#L654 and lower you would clearly see that it's code from this project, with changed functions and variables names.

    I've tried to contact author ( @kataras ) of violating package here: https://github.com/kataras/iris/issues/230, you can see the unfortunate result.

    opened by kron4eg 13
  • How to serve static files from ./public dir to the root path?

    How to serve static files from ./public dir to the root path?

    I tried the following, but it didn't work

      router.ServeFiles("/*filepath", http.Dir("public/"))
    // or
      http.Handle("/", http.FileServer(http.Dir("public/")))
    
    opened by amrnt 13
  • Add support for wildcard paths with other children

    Add support for wildcard paths with other children

    I updated the search tree, so that non-wildcard paths are resolved before wildcard paths, but both can be valid children. For instance, now you can finally have /users/roles/:role and /users/:id at the same time without issue.

    First, non-wildcard children are checked for matches. If those fail to match, then it tries the wildcard children routes. For existing compatible route configurations, there should be no (or negligible) performance impact. Many people prefer compact routes and expect a sort of precedence with httprouter, that mirrors this behavior.

    This only works for param wildcards of the form :name and doesn't change the existing *

    One thing to note, because of the prefix tree structure, if the path /books/fantasy/2007 would matched a /books/fantasy/... route because it takes priority over a /books/: category/:year template route, because exact prefixes take priority over wildcard prefixes. I think this is okay and is still a net positive. This can be merely a documentation issue.

    Overall, I think the changes capture a pretty intuitive behavior, has little to no performance impact and is something many people expect from a router. Personally, I use gin and fizz and would love to have this behavior. So I played around with it and want to share and gather your thoughts @julienschmidt.

    Related issues Looks like there's a lot of issues in this repo, but mostly in Gin. I did my best to capture them, but I'm sure that I'm missing some.

    Partially resolves https://github.com/julienschmidt/httprouter/issues/73 (doesn't work for catch-all wildcards) Resolves https://github.com/julienschmidt/httprouter/issues/91 Resolves https://github.com/julienschmidt/httprouter/issues/183 Resolves https://github.com/julienschmidt/httprouter/issues/202 Resolves https://github.com/julienschmidt/httprouter/issues/203

    Resolves https://github.com/gin-gonic/gin/issues/136 Resolves https://github.com/gin-gonic/gin/issues/205 Resolves https://github.com/gin-gonic/gin/issues/360 Resolves https://github.com/gin-gonic/gin/issues/388 Resolves https://github.com/gin-gonic/gin/issues/574 Resolves https://github.com/gin-gonic/gin/issues/957 Resolves https://github.com/gin-gonic/gin/issues/1148 Resolves https://github.com/gin-gonic/gin/issues/1065 Resolves https://github.com/gin-gonic/gin/issues/1132 Resolves https://github.com/gin-gonic/gin/issues/1301 Resolves https://github.com/gin-gonic/gin/issues/1681 Resolves https://github.com/gin-gonic/gin/issues/1730 Resolves https://github.com/gin-gonic/gin/issues/1756 Resolves https://github.com/gin-gonic/gin/issues/1990 Resolves https://github.com/gin-gonic/gin/issues/1993 Resolves https://github.com/gin-gonic/gin/issues/2005 Resolves https://github.com/gin-gonic/gin/issues/2016 Resolves https://github.com/gin-gonic/gin/issues/2062 Resolves https://github.com/gin-gonic/gin/issues/2195 Resolves https://github.com/gin-gonic/gin/issues/2289 Resolves https://github.com/gin-gonic/gin/issues/2416 Resolves https://github.com/gin-gonic/gin/issues/2465 Resolves https://github.com/gin-gonic/gin/issues/2537

    opened by rw-access 12
  • Seeing

    Seeing "panic: wildcard route conflicts with existing children" unexpectedly

    When trying to add simple routes that should not overlap, I get wildcard route conflicts.

    Simple crafted example:

    package main
    
    import (
        "fmt"
        "net/http"
        "github.com/julienschmidt/httprouter"
    )
    
    func Index(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "Welcome!\n")
    }
    
    func main() {
        router := httprouter.New()
        router.Handler("HEAD", "/:some/:thing", http.HandlerFunc(Index))
        router.Handler("GET", "/:some/:thing", http.HandlerFunc(Index))
        router.Handler("GET", "/otherthing", http.HandlerFunc(Index))
        http.Handle("/", router)
    }
    
    $ go run test.go
    
    goroutine 1 [running]:
    runtime.panic(0x1afa20, 0xc21000a600)
        /go/1.2.2/libexec/src/pkg/runtime/panic.c:266 +0xb6
    github.com/julienschmidt/httprouter.(*node).insertChild(0xc2100390c0, 0xc210000102, 0x254591, 0xc, 0xc21000a5f0)
        /build/src/github.com/julienschmidt/httprouter/tree.go:201 +0x148
    github.com/julienschmidt/httprouter.(*node).addRoute(0xc2100390c0, 0x254591, 0xc, 0xc21000a5f0)
        /build/src/github.com/julienschmidt/httprouter/tree.go:172 +0x8d5
    github.com/julienschmidt/httprouter.(*Router).Handle(0xc2100484a0, 0x247fe0, 0x3, 0x254590, 0xd, ...)
        /build/src/github.com/julienschmidt/httprouter/router.go:205 +0x15a
    github.com/julienschmidt/httprouter.(*Router).Handler(0xc2100484a0, 0x247fe0, 0x3, 0x254590, 0xd, ...)
        /build/src/github.com/julienschmidt/httprouter/router.go:215 +0x9f
    main.main()
        /some/user/path/test.go:18 +0x16d
    exit status 2
    

    In the sample code the routes that appear to conflict are /:some/:thing and /otherthing. These should not really be conflicting though, as one requires two path components, and the other is a fixed route with no wildcards. Kind of odd. Is this a bug or intended behavior?

    opened by dropwhile 11
  • Routes, named params and case sensitivity

    Routes, named params and case sensitivity

    Am I correct in assuming that the design that allows for quick route matching also restricts the routes themselves to being case sensitive?

    e.g. For the given route with a named paramter

    func Hello(w http.ResponseWriter, r *http.Request, vars map[string]string) {
        fmt.Fprintf(w, "Hello, %s!\n", vars["name"])
    }
    func main() {
        router := httprouter.New()
        router.GET("/hello/:name", Hello)
        log.Fatal(http.ListenAndServe(":12345", router))
    }
    

    Is there any way to always return Hello Joe for the following requests?

    /hello/Joe
    /HELLO/Joe
    /hElLo/Joe
    

    i.e. The desire is to have the route be case insensitive with the values of named parameters retaining their casing.

    feature 
    opened by kpowick 10
  • API to return matched router path

    API to return matched router path

    I would like to propose an API that returns the exact router path that's been matched. There are multiple situations where having the router path available would be beneficial like logging, rate limiting, etc because it will have less cardinality than the full URL with dynamic parameters.

    Given the following example

    r = httprouter.New()
    r.GET("/user/:name", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        fmt.Println("no way to get '/user/:name' here")
    })
    

    I'd like to store the state of the full route being matched in each node of the match tree and add a router.LookupRoute() (to avoid a backwards incompatible change to Lookup()) so that you can re-parse the request path and find which route matched. I'm open to other naming suggestions, or if you'd rather make a breaking change to Lookup and add the return value there.

    r = httprouter.New()
    r.GET("/user/:name", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
        _, matchedRoute, _, _ := r.LookupRoute(r.Method, r.URL.Path)
        fmt.Printf("matched %q for %q", matchedRoute, r.URL.Path)
    })
    
    opened by jehiah 9
  • End of parameter name with a dot

    End of parameter name with a dot

    router.Get("/account/:id.json", handler)
    
    params.ByName("id")
    

    Right now the parameter names end with a slash or the end of the path, how about if the dot also means the end of the parameter?

    feature 
    opened by manucorporat 9
  • Discussion: 405 Support breaks wildcard routes

    Discussion: 405 Support breaks wildcard routes

    As reported by @ydnar in #51, the 405 Support introduced in #51 breaks wildcard routes:

    This completely breaks wildcard routes for alternate methods, for example:

    r.Handle("GET", "/v1/search", search) r.Handle("OPTIONS", "/*path", handler) GET requests for /v1/search will always return a 405 with this change.

    opened by julienschmidt 9
  • Add option to thread matched route key on request context

    Add option to thread matched route key on request context

    👋 first off, thank you for such a great router!

    I have a usecase where it would be really great (in terms of visibility) when handling a request to retrieve which router match occurred and called my handler. In my instance I want to create a middleware which can automatically enrich traces with this router path.

    This is my little attempt to surface that information. There is probably a cleaner way than my approach.

    Also here are the benchmarks:

    goos: darwin
    goarch: amd64
    pkg: github.com/julienschmidt/httprouter
    BenchmarkAllowed/Global-16         	300000000	         5.56 ns/op	       0 B/op	       0 allocs/op
    BenchmarkAllowed/Path-16           	10000000	       137 ns/op	      32 B/op	       1 allocs/op
    PASS
    ok  	github.com/julienschmidt/httprouter	3.752s
    

    OK I just saw https://github.com/julienschmidt/httprouter/pull/139 so perhaps this change is a little undesireable or just unlikely to go through. But I am going to try anyway. This at least offers an interface which is backwards compatible with the existing one.

    feature 
    opened by GeorgeMac 8
  • v1.2 release timeline?

    v1.2 release timeline?

    Hi, is there a timeline for the release of 1.2? I see there are still a few outstanding commits on the milestone, but 1.1 points to a commit about two years old. Users of dependency managers like glide will likely pin their dependency on httprouter to the latest release (1.1) and get a very old version of httprouter.

    Is it reasonable to either finish the 1.2 blockers soon or push them to a later release?

    opened by rcorre 8
  • Question: will re-registering a handler work properly?

    Question: will re-registering a handler work properly?

    Hi! I need a router that is able to re-register (or remove) a handler. Adding the remove path function looks too complex a task, however, removing this condition seems to allow re-registration of a HandleFunc easily. Is there a pitfall that I do not see?

    opened by dchukmasov 0
  • httprouter.ParamsWithContext(r.Context()) is returning []

    httprouter.ParamsWithContext(r.Context()) is returning []

    Using alice with httprouter to chain middleware and wrapping params before passing it to the middleware function.

    func (s *Server) wrap(next http.Handler) httprouter.Handle {
    	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
    		ctx := context.WithValue(r.Context(), params, ps)
    		next.ServeHTTP(w, r.WithContext(ctx))
    	}
    }
    
    / routes configure server API endpoints
    func (s *Server) routes() http.Handler {
    	r := httprouter.New()
    	secure := alice.New(s.authenticateWithIDMS)
    
    	// unsecured end points
    	r.HandlerFunc(http.MethodGet, "/api/v2/projects/:id", s.getProject)
    
    	// secured end points
    	r.GET("/api/v2/projects/:id", s.wrap(secure.ThenFunc(s.getProject)))
    
    	return s.enableCORS(r)
    }
    
    func (s *Server) enableCORS(next http.Handler) http.Handler {
    	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    		w.Header().Set("Access-Control-Allow-Origin", "*")
    		w.Header().Set("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,PATCH")
    		w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
    
    		next.ServeHTTP(w, r)
    	})
    }
    
    // getProject returns all the projects as an API response
    func (s *Server) getProject(w http.ResponseWriter, r *http.Request) {
    	params := httprouter.ParamsFromContext(r.Context())
    	log.Println(params)
    
    	id, err := strconv.Atoi(params.ByName("id"))
    	if err != nil {
    		s.logger.Println(errors.New("invalid movie id : "), err)
    		utils.ErrorJSON(w, err)
    		return
    	}
    
    	utils.WriteJSON(w, http.StatusOK, id, "data")
    }
    

    Inside getProjects(), r.Context().Value("params") returns [{id 1}] but httprouter.ParamsFromContext(r.Context()) returns [] when I use the s.wrap() call, but if I do not use it then the params are passed properly.

    Any pointers?

    opened by samirprakash 0
  • Why make catchAll form so special

    Why make catchAll form so special

    If I add a route "/*a", the tree should be "{path:""}->{path:""}->{path:"/*a"}". Why not make it just like param form? I feel much confused, I just don't understand why it should be designed like this. Look forward to your reply, thanks.

    opened by superbest777 2
  • panic: '/hello/:name' in new path '/hello/:name' conflicts with existing wildcar

    panic: '/hello/:name' in new path '/hello/:name' conflicts with existing wildcar

    `package main

    import ( "fmt" "github.com/julienschmidt/httprouter" "log" "net/http" )

    func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name")) }

    func main() { router := httprouter.New() router.ServeFiles("/*filepath", http.Dir("./templates")) router.GET("/hello/:name", Hello) log.Fatal(http.ListenAndServe(":8080", router)) }`

    panic: '/hello/:name' in new path '/hello/:name' conflicts with existing wildcard '/*filepath' in existing prefix '/*filepath'

    opened by Nemnon 0
  • is it possible to get the registered path?

    is it possible to get the registered path?

    I'm about to use httprouter in a http api gateway, and use httprouter to match path. i do not need a handle function, so i register paths with an empty handler:

    router := httprouter.New()
    router.Handle("GET","/user/:user_id/basic", func(writer http.ResponseWriter,
    			request *http.Request, params httprouter.Params) {})
    router.Handle("GET","/user/:user_id/feature", func(writer http.ResponseWriter,
    			request *http.Request, params httprouter.Params) {})
    

    then use LookUp method to match path

    router.LookUp("GET","/user/1234/basic")
    

    the LookUp method only returns handler, params and tsr currently. what i need is the matched path /user/:user_id/basic to get the upstream server which is related to the path.

    opened by yumxu 2
Releases(v1.3.0)
  • v1.3.0(Sep 30, 2019)

    • Fixed license wording to be properly detected as the BSD 3-Clause License
    • Fixed case-insensitive path lookup for multibyte runes (#263)
    • Fixed a bug in the calculation of the maximum number of parameters (#261)
    • Added a check preventing adding handlers for an empty path, avoid a out-of-range panic (#204)
    • Fixed a wildcard conflict check (#172)
    • The methods in Allowed headers are now sorted (#248)
    • Added an option to add a global handler for automatic responses to OPTIONS requests (#156, #200, #214, #260)
    • Minor performance optimizations and documentation fixes

    The required minimum Go version is now 1.7.

    Thanks to everyone who has sent pull-requests, reported issues, or contributed in any other way!

    Source code(tar.gz)
    Source code(zip)
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

招牌疯子 866 Jul 11, 2022
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 Apr 10, 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 251 May 30, 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 130 Jul 24, 2022
Go HTTP request router and web framework benchmark

Go HTTP Router Benchmark This benchmark suite aims to compare the performance of HTTP request routers for Go by implementing the routing structure of

Peter Kieltyka 24 Aug 2, 2022
High-speed, flexible tree-based HTTP router for Go.

httptreemux 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

Daniel Imfeld 549 Jul 25, 2022
A benchmark suite aims to compare the performance of HTTP request routers for Go

Go HTTP Router Benchmark This benchmark suite aims to compare the performance of HTTP request routers for Go by implementing the routing structure of

null 3 Oct 25, 2021
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
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
: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.1k Aug 4, 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 441 Aug 8, 2022
Pure is a fast radix-tree based HTTP router

package pure Pure is a fast radix-tree based HTTP router that sticks to the native implementations of Go's "net/http" package; in essence, keeping the

Go Playgound 128 Aug 8, 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 105 Mar 21, 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 Jul 16, 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 11.9k Aug 6, 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 458 Jul 29, 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 34 Jul 27, 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