{"id":37115271,"url":"https://github.com/rs/httprouter","last_synced_at":"2026-01-14T13:32:25.245Z","repository":{"id":66040884,"uuid":"48818299","full_name":"rs/httprouter","owner":"rs","description":"A high performance HTTP request router that scales well","archived":false,"fork":true,"pushed_at":"2015-12-28T22:21:29.000Z","size":271,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-05-09T10:18:22.100Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://godoc.org/github.com/julienschmidt/httprouter","language":"Go","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"julienschmidt/httprouter","license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-12-30T20:29:14.000Z","updated_at":"2020-05-09T16:12:59.000Z","dependencies_parsed_at":"2023-02-19T22:15:26.471Z","dependency_job_id":null,"html_url":"https://github.com/rs/httprouter","commit_stats":null,"previous_names":[],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/rs/httprouter","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fhttprouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fhttprouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fhttprouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fhttprouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rs","download_url":"https://codeload.github.com/rs/httprouter/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fhttprouter/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28421239,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-14T13:30:50.153Z","status":"ssl_error","status_checked_at":"2026-01-14T13:29:08.907Z","response_time":107,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-01-14T13:32:24.561Z","updated_at":"2026-01-14T13:32:25.234Z","avatar_url":"https://github.com/rs.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.png?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage](http://gocover.io/_badge/github.com/julienschmidt/httprouter?0)](http://gocover.io/github.com/julienschmidt/httprouter) [![GoDoc](http://godoc.org/github.com/julienschmidt/httprouter?status.png)](http://godoc.org/github.com/julienschmidt/httprouter)\n\nHttpRouter is a lightweight high performance HTTP request router\n(also called *multiplexer* or just *mux* for short) for [Go](http://golang.org/).\n\nIn contrast to the [default mux](http://golang.org/pkg/net/http/#ServeMux) of Go's net/http package, this router supports\nvariables in the routing pattern and matches against the request method.\nIt also scales better.\n\nThe router is optimized for high performance and a small memory footprint.\nIt scales well even with very long paths and a large number of routes.\nA compressing dynamic trie (radix tree) structure is used for efficient matching.\n\n## Features\n**Only explicit matches:** With other routers, like [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux),\na requested URL path could match multiple patterns. Therefore they have some\nawkward pattern priority rules, like *longest match* or *first registered,\nfirst matched*. By design of this router, a request can only match exactly one\nor no route. As a result, there are also no unintended matches, which makes it\ngreat for SEO and improves the user experience.\n\n**Stop caring about trailing slashes:** Choose the URL style you like, the\nrouter automatically redirects the client if a trailing slash is missing or if\nthere is one extra. Of course it only does so, if the new path has a handler.\nIf you don't like it, you can [turn off this behavior](http://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash).\n\n**Path auto-correction:** Besides detecting the missing or additional trailing\nslash at no extra cost, the router can also fix wrong cases and remove\nsuperfluous path elements (like `../` or `//`).\nIs [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users?\nHttpRouter can help him by making a case-insensitive look-up and redirecting him\nto the correct URL.\n\n**Parameters in your routing pattern:** Stop parsing the requested URL path,\njust give the path segment a name and the router delivers the dynamic value to\nyou. Because of the design of the router, path parameters are very cheap.\n\n**Zero Garbage:** The matching and dispatching process generates zero bytes of\ngarbage. In fact, the only heap allocations that are made, is by building the\nslice of the key-value pairs for path parameters. If the request path contains\nno parameters, not a single heap allocation is necessary.\n\n**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark).\nSee below for technical details of the implementation.\n\n**No more server crashes:** You can set a [Panic handler](http://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics\noccurring during handling a HTTP request. The router then recovers and lets the\nPanicHandler log what happened and deliver a nice error page.\n\nOf course you can also set **custom [NotFound](http://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and  [MethodNotAllowed](http://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](http://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles).\n\n## Usage\nThis is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.\n\nLet's start with a trivial example:\n```go\npackage main\n\nimport (\n    \"fmt\"\n    \"github.com/julienschmidt/httprouter\"\n    \"net/http\"\n    \"log\"\n)\n\nfunc Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n    fmt.Fprint(w, \"Welcome!\\n\")\n}\n\nfunc Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n    fmt.Fprintf(w, \"hello, %s!\\n\", ps.ByName(\"name\"))\n}\n\nfunc main() {\n    router := httprouter.New()\n    router.GET(\"/\", Index)\n    router.GET(\"/hello/:name\", Hello)\n\n    log.Fatal(http.ListenAndServe(\":8080\", router))\n}\n```\n\n### Named parameters\nAs you can see, `:name` is a *named parameter*.\nThe values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s.\nYou can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method:\n`:name` can be retrived by `ByName(\"name\")`.\n\nNamed parameters only match a single path segment:\n```\nPattern: /user/:user\n\n /user/gordon              match\n /user/you                 match\n /user/gordon/profile      no match\n /user/                    no match\n```\n\n**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.\n\n### Catch-All parameters\nThe second type are *catch-all* parameters and have the form `*name`.\nLike the name suggests, they match everything.\nTherefore they must always be at the **end** of the pattern:\n```\nPattern: /src/*filepath\n\n /src/                     match\n /src/somefile.go          match\n /src/subdir/somefile.go   match\n```\n\n## How does it work?\nThe router relies on a tree structure which makes heavy use of *common prefixes*,\nit is basically a *compact* [*prefix tree*](http://en.wikipedia.org/wiki/Trie)\n(or just [*Radix tree*](http://en.wikipedia.org/wiki/Radix_tree)).\nNodes with a common prefix also share a common parent. Here is a short example\nwhat the routing tree for the `GET` request method could look like:\n\n```\nPriority   Path             Handle\n9          \\                *\u003c1\u003e\n3          ├s               nil\n2          |├earch\\         *\u003c2\u003e\n1          |└upport\\        *\u003c3\u003e\n2          ├blog\\           *\u003c4\u003e\n1          |    └:post      nil\n1          |         └\\     *\u003c5\u003e\n2          ├about-us\\       *\u003c6\u003e\n1          |        └team\\  *\u003c7\u003e\n1          └contact\\        *\u003c8\u003e\n```\nEvery `*\u003cnum\u003e` represents the memory address of a handler function (a pointer).\nIf you follow a path trough the tree from the root to the leaf, you get the\ncomplete route path, e.g `\\blog\\:post\\`, where `:post` is just a placeholder\n([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a\ntree structure also allows us to use dynamic parts like the `:post` parameter,\nsince we actually match against the routing patterns instead of just comparing\nhashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark),\nthis works very well and efficient.\n\nSince URL paths have a hierarchical structure and make use only of a limited set\nof characters (byte values), it is very likely that there are a lot of common\nprefixes. This allows us to easily reduce the routing into ever smaller problems.\nMoreover the router manages a separate tree for every request method.\nFor one thing it is more space efficient than holding a method-\u003ehandle map in\nevery single node, for another thing is also allows us to greatly reduce the\nrouting problem before even starting the look-up in the prefix-tree.\n\nFor even better scalability, the child nodes on each tree level are ordered by\npriority, where the priority is just the number of handles registered in sub\nnodes (children, grandchildren, and so on..).\nThis helps in two ways:\n\n1. Nodes which are part of the most routing paths are evaluated first. This\nhelps to make as much routes as possible to be reachable as fast as possible.\n2. It is some sort of cost compensation. The longest reachable path (highest\ncost) can always be evaluated first. The following scheme visualizes the tree\nstructure. Nodes are evaluated from top to bottom and from left to right.\n\n```\n├------------\n├---------\n├-----\n├----\n├--\n├--\n└-\n```\n\n\n## Why doesn't this work with http.Handler?\n**It does!** The router itself implements the http.Handler interface.\nMoreover the router provides convenient [adapters for http.Handler](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [http.HandlerFunc](http://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s\nwhich allows them to be used as a [httprouter.Handle](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route.\nThe only disadvantage is, that no parameter values can be retrieved when a\nhttp.Handler or http.HandlerFunc is used, since there is no efficient way to\npass the values with the existing function parameters.\nTherefore [httprouter.Handle](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) has a third function parameter.\n\nJust 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.\n\n\n## Where can I find Middleware *X*?\nThis package just provides a very efficient request router with a few extra\nfeatures. The router is just a [http.Handler](http://golang.org/pkg/net/http/#Handler),\nyou can chain any http.Handler compatible middleware before the router,\nfor example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers).\nOr you could [just write your own](http://justinas.org/writing-http-middleware-in-go/),\nit's very easy!\n\nAlternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter).\n\n### Multi-domain / Sub-domains\nHere is a quick example: Does your server serve multiple domains / hosts?\nYou want to use sub-domains?\nDefine a router per host!\n```go\n// We need an object that implements the http.Handler interface.\n// Therefore we need a type for which we implement the ServeHTTP method.\n// We just use a map here, in which we map host names (with port) to http.Handlers\ntype HostSwitch map[string]http.Handler\n\n// Implement the ServerHTTP method on our new type\nfunc (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t// Check if a http.Handler is registered for the given host.\n\t// If yes, use it to handle the request.\n\tif handler := hs[r.Host]; handler != nil {\n\t\thandler.ServeHTTP(w, r)\n\t} else {\n\t\t// Handle host names for wich no handler is registered\n\t\thttp.Error(w, \"Forbidden\", 403) // Or Redirect?\n\t}\n}\n\nfunc main() {\n\t// Initialize a router as usual\n\trouter := httprouter.New()\n\trouter.GET(\"/\", Index)\n\trouter.GET(\"/hello/:name\", Hello)\n\n\t// Make a new HostSwitch and insert the router (our http handler)\n\t// for example.com and port 12345\n\ths := make(HostSwitch)\n\ths[\"example.com:12345\"] = router\n\n\t// Use the HostSwitch to listen and serve on port 12345\n\tlog.Fatal(http.ListenAndServe(\":12345\", hs))\n}\n```\n\n### Basic Authentication\nAnother quick example: Basic Authentication (RFC 2617) for handles:\n\n```go\npackage main\n\nimport (\n    \"bytes\"\n    \"encoding/base64\"\n    \"fmt\"\n    \"github.com/julienschmidt/httprouter\"\n    \"net/http\"\n    \"log\"\n    \"strings\"\n)\n\nfunc BasicAuth(h httprouter.Handle, user, pass []byte) httprouter.Handle {\n\treturn func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\t\tconst basicAuthPrefix string = \"Basic \"\n\n\t\t// Get the Basic Authentication credentials\n\t\tauth := r.Header.Get(\"Authorization\")\n\t\tif strings.HasPrefix(auth, basicAuthPrefix) {\n\t\t\t// Check credentials\n\t\t\tpayload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):])\n\t\t\tif err == nil {\n\t\t\t\tpair := bytes.SplitN(payload, []byte(\":\"), 2)\n\t\t\t\tif len(pair) == 2 \u0026\u0026\n\t\t\t\t\tbytes.Equal(pair[0], user) \u0026\u0026\n\t\t\t\t\tbytes.Equal(pair[1], pass) {\n\n\t\t\t\t\t// Delegate request to the given handle\n\t\t\t\t\th(w, r, ps)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Request Basic Authentication otherwise\n\t\tw.Header().Set(\"WWW-Authenticate\", \"Basic realm=Restricted\")\n\t\thttp.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)\n\t}\n}\n\nfunc Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n    fmt.Fprint(w, \"Not protected!\\n\")\n}\n\nfunc Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n    fmt.Fprint(w, \"Protected!\\n\")\n}\n\nfunc main() {\n    user := []byte(\"gordon\")\n    pass := []byte(\"secret!\")\n    \n    router := httprouter.New()\n    router.GET(\"/\", Index)\n    router.GET(\"/protected/\", BasicAuth(Protected, user, pass))\n\n    log.Fatal(http.ListenAndServe(\":8080\", router))\n}\n```\n\n## Chaining with the NotFound handler\n\n**NOTE: It might be required to set [Router.HandleMethodNotAllowed](http://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.**\n\nYou can use another [http.Handler](http://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [Router.NotFound](http://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining.\n\n### Static files\nThe `NotFound` handler can for example be used to serve static files from the root path `/` (like an index.html file along with other assets):\n```go\n// Serve static files from the ./public directory\nrouter.NotFound = http.FileServer(http.Dir(\"public\"))\n```\n\nBut 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`.\n\n## Web Frameworks based on HttpRouter\nIf 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:\n* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework\n* [api2go](https://github.com/univedo/api2go): A JSON API Implementation for Go\n* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance\n* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go\n* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine\n* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow\n* [httpway](http://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support\n* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context\n* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba\n* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang\n* [Roxanna](https://github.com/iamthemuffinman/Roxanna): An amalgamation of httprouter, better logging, and hot reload\n* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fhttprouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frs%2Fhttprouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fhttprouter/lists"}