{"id":13764098,"url":"https://github.com/rs/xmux","last_synced_at":"2025-10-14T06:03:59.318Z","repository":{"id":41512142,"uuid":"47995080","full_name":"rs/xmux","owner":"rs","description":"xmux is a httprouter fork on top of xhandler (net/context aware)","archived":false,"fork":false,"pushed_at":"2017-06-09T18:54:18.000Z","size":46,"stargazers_count":99,"open_issues_count":2,"forks_count":11,"subscribers_count":6,"default_branch":"master","last_synced_at":"2025-04-15T11:17:29.934Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"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-14T19:01:05.000Z","updated_at":"2024-12-14T15:35:29.000Z","dependencies_parsed_at":"2022-09-08T14:11:15.055Z","dependency_job_id":null,"html_url":"https://github.com/rs/xmux","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/rs/xmux","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fxmux","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fxmux/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fxmux/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fxmux/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rs","download_url":"https://codeload.github.com/rs/xmux/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fxmux/sbom","scorecard":{"id":786816,"data":{"date":"2025-08-11","repo":{"name":"github.com/rs/xmux","commit":"d379109ea970568fad9197dd3795934ba1a85c05"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3.1,"checks":[{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Code-Review","score":1,"reason":"Found 3/28 approved changesets -- score normalized to 1","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"License","score":9,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Warn: project license file does not contain an FSF or OSI license."],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}},{"name":"SAST","score":0,"reason":"SAST tool is not run on all commits -- score normalized to 0","details":["Warn: 0 commits out of 5 are checked with a SAST tool"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}}]},"last_synced_at":"2025-08-23T06:18:54.620Z","repository_id":41512142,"created_at":"2025-08-23T06:18:54.620Z","updated_at":"2025-08-23T06:18:54.620Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279017967,"owners_count":26086239,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-14T02:00:06.444Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":"2024-08-03T15:01:13.721Z","updated_at":"2025-10-14T06:03:59.294Z","avatar_url":"https://github.com/rs.png","language":"Go","funding_links":[],"categories":["Web Frameworks","Web框架","路由","Routers","XML"],"sub_categories":["Routers","路由器","创建http中间件的代码库","路由","Advanced Console UIs"],"readme":"# Xmux\n\n[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/xmux) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/xmux/master/LICENSE) [![Build Status](https://travis-ci.org/rs/xmux.svg?branch=master)](https://travis-ci.org/rs/xmux) [![Coverage](http://gocover.io/_badge/github.com/rs/xmux)](http://gocover.io/github.com/rs/xmux)\n\nXmux is a lightweight high performance HTTP request muxer on top [xhandler](https://github.com/rs/xhandler). Xmux gets its speed from the fork of the amazing [httprouter](https://github.com/julienschmidt/httprouter). Route parameters are stored in `context` instead of being passed as an additional parameter.\n\nIn contrast to the [default mux](http://golang.org/pkg/net/http/#ServeMux) of Go's `net/http` package, this muxer supports variables in the routing pattern and matches against the request method. It also scales better.\n\nThe muxer 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.\n\n## Features\n\n**Only explicit matches:** With other muxers, like [http.ServeMux](http://golang.org/pkg/net/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.\n\n**Stop caring about trailing slashes:** Choose the URL style you like, the muxer 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](http://godoc.org/github.com/rs/xmux#Mux.RedirectTrailingSlash).\n\n**Path auto-correction:** Besides detecting the missing or additional trailing slash at no extra cost, the muxer can also fix wrong cases and remove superfluous path elements (like `../` or `//`). Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users? Xmux can help him by making a case-insensitive look-up and redirecting him to the correct URL.\n\n**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.\n\n**RouteGroups:** A way to create [groups of routes](http://godoc.org/github.com/rs/xmux#Mux.NewGroup) without incurring any per-request overhead.\n\n**Zero Garbage:** The matching and dispatching process generates zero bytes of garbage. In fact, the only heap allocations that are made, is by building the slice of the key-value pairs for path parameters and the `context` instance to store them in the context. If the request path contains no parameters, not a single heap allocation is necessary.\n\n**No more server crashes:** You can set a [Panic handler](http://godoc.org/github.com/rs/xmux#Mux.PanicHandler) 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.\n\nOf course you can also set **custom [NotFound](http://godoc.org/github.com/rs/xmux#Mux.NotFound) and  [MethodNotAllowed](http://godoc.org/github.com/rs/xmux#Mux.MethodNotAllowed) handlers**.\n\n## Usage\n\nThis is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/rs/xmux) for details.\n\nLet's start with a trivial example:\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"context\"\n\n\t\"github.com/rs/xhandler\"\n\t\"github.com/rs/xmux\"\n)\n\nfunc Index(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}\n\nfunc Hello(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"hello, %s!\\n\", xmux.Param(ctx, \"name\"))\n}\n\nfunc main() {\n\tmux := xmux.New()\n\tmux.GET(\"/\", xhandler.HandlerFuncC(Index))\n\tmux.GET(\"/hello/:name\", xhandler.HandlerFuncC(Hello))\n\n\tlog.Fatal(http.ListenAndServe(\":8080\", xhandler.New(context.Background(), mux)))\n}\n```\n\nYou may also chain middleware using `xhandler.Chain`:\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/rs/xhandler\"\n\t\"github.com/rs/xmux\"\n)\n\nfunc main() {\n\tc := xhandler.Chain{}\n\n\t// Append a context-aware middleware handler\n\tc.UseC(xhandler.CloseHandler)\n\n\t// Another context-aware middleware handler\n\tc.UseC(xhandler.TimeoutHandler(2 * time.Second))\n\n\tmux := xmux.New()\n\n\t// Use c.Handler to terminate the chain with your final handler\n\tmux.GET(\"/welcome/:name\", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) {\n\t\tfmt.Fprintf(w, \"Welcome %s!\", xmux.Param(ctx, \"name\"))\n\t}))\n\n\tif err := http.ListenAndServe(\":8080\", c.Handler(mux)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\n### Named parameters\n\nAs you can see, `:name` is a *named parameter*. The values are accessible via `xmux.Params(ctx)`, which returns `xmux.ParamHolder`.\nYou can get the value of a parameter by its name using `Get(name)` method:\n\n```go\nuser := xmux.Params(ctx).Get(\"user\")\n```\n\nor using `xmux.Param(ctx, name)` shortcut:\n\n```go\nuser := xmux.Param(ctx, \"user\")\n```\n\nNamed parameters only match a single path segment:\n\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 muxer 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\n\nThe 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:\n\n```\nPattern: /src/*filepath\n\n /src/                     match\n /src/somefile.go          match\n /src/subdir/somefile.go   match\n```\n\n## Benchmarks\n\nThanks to [Julien Schmidt](https://github.com/julienschmidt) excellent [HTTP routing benchmark](https://github.com/julienschmidt/go-http-routing-benchmark), we can see that xhandler's muxer is pretty close to `httprouter` as it is a fork of it. The small overhead is due to the `context` allocation used to store route parameters. It still outperform other routers, thanks to amazing `httprouter`'s radix tree based matcher.\n\n```\nBenchmarkXhandler_APIStatic-8   \t50000000\t        39.6 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkChi_APIStatic-8        \t 3000000\t       439 ns/op\t     144 B/op\t       5 allocs/op\nBenchmarkGoji_APIStatic-8       \t 5000000\t       272 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkHTTPRouter_APIStatic-8 \t50000000\t        37.3 ns/op\t       0 B/op\t       0 allocs/op\n\nBenchmarkXhandler_APIParam-8    \t 5000000\t       328 ns/op\t     160 B/op\t       4 allocs/op\nBenchmarkChi_APIParam-8         \t 2000000\t       675 ns/op\t     432 B/op\t       6 allocs/op\nBenchmarkGoji_APIParam-8        \t 2000000\t       692 ns/op\t     336 B/op\t       2 allocs/op\nBenchmarkHTTPRouter_APIParam-8  \t10000000\t       166 ns/op\t      64 B/op\t       1 allocs/op\n\nBenchmarkXhandler_API2Params-8  \t 5000000\t       362 ns/op\t     160 B/op\t       4 allocs/op\nBenchmarkChi_API2Params-8       \t 2000000\t       814 ns/op\t     432 B/op\t       6 allocs/op\nBenchmarkGoji_API2Params-8      \t 2000000\t       680 ns/op\t     336 B/op\t       2 allocs/op\nBenchmarkHTTPRouter_API2Params-8\t10000000\t       183 ns/op\t      64 B/op\t       1 allocs/op\n\nBenchmarkXhandler_APIAll-8      \t  200000\t      6473 ns/op\t    2176 B/op\t      64 allocs/op\nBenchmarkChi_APIAll-8           \t  100000\t     17261 ns/op\t    8352 B/op\t     146 allocs/op\nBenchmarkGoji_APIAll-8          \t  100000\t     15052 ns/op\t    5377 B/op\t      32 allocs/op\nBenchmarkHTTPRouter_APIAll-8    \t  500000\t      3716 ns/op\t     640 B/op\t      16 allocs/op\n\nBenchmarkXhandler_Param1-8      \t 5000000\t       271 ns/op\t     128 B/op\t       4 allocs/op\nBenchmarkChi_Param1-8           \t 2000000\t       620 ns/op\t     432 B/op\t       6 allocs/op\nBenchmarkGoji_Param1-8          \t 3000000\t       522 ns/op\t     336 B/op\t       2 allocs/op\nBenchmarkHTTPRouter_Param1-8    \t20000000\t       112 ns/op\t      32 B/op\t       1 allocs/op\n\nBenchmarkXhandler_Param5-8      \t 3000000\t       414 ns/op\t     256 B/op\t       4 allocs/op\nBenchmarkChi_Param5-8           \t 1000000\t      1204 ns/op\t     432 B/op\t       6 allocs/op\nBenchmarkGoji_Param5-8          \t 2000000\t       847 ns/op\t     336 B/op\t       2 allocs/op\nBenchmarkHTTPRouter_Param5-8    \t 5000000\t       247 ns/op\t     160 B/op\t       1 allocs/op\n\nBenchmarkXhandler_Param20-8     \t 2000000\t       747 ns/op\t     736 B/op\t       4 allocs/op\nBenchmarkChi_Param20-8          \t 2000000\t       746 ns/op\t     736 B/op\t       4 allocs/op\nBenchmarkGoji_Param20-8         \t  500000\t      2439 ns/op\t    1247 B/op\t       2 allocs/op\nBenchmarkHTTPRouter_Param20-8   \t 3000000\t       585 ns/op\t     640 B/op\t       1 allocs/op\n\nBenchmarkXhandler_ParamWrite-8  \t 5000000\t       404 ns/op\t     144 B/op\t       5 allocs/op\nBenchmarkChi_ParamWrite-8       \t 3000000\t       407 ns/op\t     144 B/op\t       5 allocs/op\nBenchmarkGoji_ParamWrite-8      \t 2000000\t       594 ns/op\t     336 B/op\t       2 allocs/op\nBenchmarkHTTPRouter_ParamWrite-8\t10000000\t       166 ns/op\t      32 B/op\t       1 allocs/op\n```\n\nYou can run this benchmark by executing the following commands at the root of `xmux` repository:\n\n```go\ngo get -t ./bench/routers\ngo test ./bench/routers -bench .\n```\n\n## How does it work?\n\nThe muxer relies on a tree structure which makes heavy use of *common prefixes*, it is basically a *compact* [*prefix tree*](http://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](http://en.wikipedia.org/wiki/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:\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```\n\nEvery `*\u003cnum\u003e` 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*](#named-parameters)) 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](https://github.com/julienschmidt/go-http-routing-benchmark), this works very well and efficient.\n\nSince 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-\u003ehandle map in every single node, for another thing is also allows us to greatly reduce the routing 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 priority, where the priority is just the number of handles registered in sub nodes (children, grandchildren, and so on..). This helps in two ways:\n\n1. 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.\n2. 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.\n\n```\n├------------\n├---------\n├-----\n├----\n├--\n├--\n└-\n```\n\n## Why doesn't this work with http.Handler?\n\n**It does!** The router itself implements the http.Handler interface. Moreover the router provides convenient [adapters for http.Handler](http://godoc.org/github.com/rs/xmux#Mux.Handle)s and [http.HandlerFunc](http://godoc.org/github.com/rs/xmux#Mux.HandleFunc)s which allows them to be used as a [xhandler.HandlerC](http://godoc.org/github.com/rs/xhandler#HandlerC) when registering a route. The only disadvantage is, that no `context` and thus no parameter values can be retrieved when a `http.Handler` or `http.HandlerFunc` is used.\n\n## Where can I find Middleware *X*?\n\nThis package just provides a very efficient request muxer with a few extra features. The muxer is just a [xhandler.HandlerC](https://godoc.org/github.com/rs/xhandler#HandlerC), you can chain any `http.Handler` or `xhandler.HandlerC` compatible middleware before the router, for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers). Or you could [just write your own](http://justinas.org/writing-http-middleware-in-go/), it's very easy!\n\n### Multi-domain / Sub-domains\n\nHere is a quick example: Does your server serve multiple domains / hosts? You want to use sub-domains? Define a router per host!\n\n```go\n// We need an object that implements the xhandler.HandlerC 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 xhandler.HandlerC\ntype HostSwitch map[string]xhandler.HandlerC\n\n// Implement the ServerHTTP method on our new type\nfunc (hs HostSwitch) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\t// Check if a xhandler.HandlerC 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.ServeHTTPC(ctx, 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\tc := xhandler.Chain{}\n\n\t// Initialize a muxer as usual\n\tmux := xmux.New()\n\tmux.GET(\"/\", Index)\n\tmux.GET(\"/hello/:name\", Hello)\n\n\t// Make a new HostSwitch and insert the muxer (our http handler)\n\t// for example.com and port 12345\n\ths := make(HostSwitch)\n\ths[\"example.com:12345\"] = mux\n\n\t// Use the HostSwitch to listen and serve on port 12345\n\tif err := http.ListenAndServe(\":12345\", c.Handler(hs)); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\n### Basic Authentication\nAnother quick example: Basic Authentication (RFC 2617) for handles:\n\n```go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"encoding/base64\"\n\t\"fmt\"\n\t\"log\"\n\t\"net/http\"\n\t\"strings\"\n\n\t\"github.com/rs/xhandler\"\n\t\"github.com/rs/xmux\"\n)\n\nfunc BasicAuth(user, pass []byte, next xhandler.HandlerC) xhandler.HandlerC {\n\treturn xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {\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 next handler\n\t\t\t\t\tnext.ServeHTTPC(ctx, w, r)\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(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Not protected!\\n\")\n}\n\nfunc Protected(ctx context.Context, w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Protected!\\n\")\n}\n\nfunc main() {\n\tuser := []byte(\"gordon\")\n\tpass := []byte(\"secret!\")\n\n\tc := xhandler.Chain{}\n\tmux := xmux.New()\n\tmux.GET(\"/\", xhandler.HandlerFuncC(Index))\n\tmux.GET(\"/protected/\", BasicAuth(user, pass, xhandler.HandlerFuncC(Protected)))\n\n\tlog.Fatal(http.ListenAndServe(\":8080\", c.Handler(mux)))\n}\n```\n\n## Licenses\n\nAll source code is licensed under the [BSD License](https://raw.github.com/rs/xhandler/master/LICENSE).\n\nXmux is forked from [httprouter](https://github.com/julienschmidt/httprouter) with [BSD License](https://github.com/julienschmidt/httprouter/blob/master/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fxmux","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frs%2Fxmux","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fxmux/lists"}