chi
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
chi is a lightweight, idiomatic and composable router for building Go HTTP services. It'sespecially good at helping you write large REST API services that are kept maintainable as yourproject grows and changes.chi is built on the newcontext package introduced in Go 1.7 tohandle signaling, cancelation and request-scoped values across a handler chain.
The focus of the project has been to seek out an elegant and comfortable design for writingREST API servers, written during the development of the Pressly API service that powers ourpublic API service, which in turn powers all of our client-side applications.
The key considerations of chi's design are: project structure, maintainability, standard httphandlers (stdlib-only), developer productivity, and deconstructing a large system into many smallparts. The core routergithub.com/go-chi/chi is quite small (less than 1000 LOC), but we've alsoincluded some useful/optional subpackages:middleware,renderanddocgen. We hope you enjoy it too!
Install
go get -u github.com/go-chi/chi/v5Features
- Lightweight - cloc'd in ~1000 LOC for the chi router
- Fast - yes, seebenchmarks
- 100% compatible with net/http - use any http or middleware pkg in the ecosystem that is also compatible with
net/http - Designed for modular/composable APIs - middlewares, inline middlewares, route groups and sub-router mounting
- Context control - built on new
contextpackage, providing value chaining, cancellations and timeouts - Robust - in production at Pressly, Cloudflare, Heroku, 99Designs, and many others (seediscussion)
- Doc generation -
docgenauto-generates routing documentation from your source to JSON or Markdown - Go.mod support - as of v5, go.mod support (seeCHANGELOG)
- No external dependencies - plain ol' Go stdlib + net/http
Examples
See_examples/ for a variety of examples.
As easy as:
package mainimport ("net/http""github.com/go-chi/chi/v5""github.com/go-chi/chi/v5/middleware")func main() {r := chi.NewRouter()r.Use(middleware.Logger)r.Get("/", func(w http.ResponseWriter, r *http.Request) {w.Write([]byte("welcome"))})http.ListenAndServe(":3000", r)}REST Preview:
Here is a little preview of what routing looks like with chi. Also take a look at the generated routing docsin JSON (routes.json) and inMarkdown (routes.md).
I highly recommend reading the source of theexamples listedabove, they will show you all the features of chi and serve as a good form of documentation.
import ( //... "context" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware")func main() { r := chi.NewRouter() // A good base middleware stack r.Use(middleware.RequestID) r.Use(middleware.RealIP) r.Use(middleware.Logger) r.Use(middleware.Recoverer) // Set a timeout value on the request context (ctx), that will signal // through ctx.Done() that the request has timed out and further // processing should be stopped. r.Use(middleware.Timeout(60 * time.Second)) r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hi")) }) // RESTy routes for "articles" resource r.Route("/articles", func(r chi.Router) { r.With(paginate).Get("/", listArticles) // GET /articles r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017 r.Post("/", createArticle) // POST /articles r.Get("/search", searchArticles) // GET /articles/search // Regexp url parameters: r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug) // GET /articles/home-is-toronto // Subrouters: r.Route("/{articleID}", func(r chi.Router) { r.Use(ArticleCtx) r.Get("/", getArticle) // GET /articles/123 r.Put("/", updateArticle) // PUT /articles/123 r.Delete("/", deleteArticle) // DELETE /articles/123 }) }) // Mount the admin sub-router r.Mount("/admin", adminRouter()) http.ListenAndServe(":3333", r)}func ArticleCtx(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { articleID := chi.URLParam(r, "articleID") article, err := dbGetArticle(articleID) if err != nil { http.Error(w, http.StatusText(404), 404) return } ctx := context.WithValue(r.Context(), "article", article) next.ServeHTTP(w, r.WithContext(ctx)) })}func getArticle(w http.ResponseWriter, r *http.Request) { ctx := r.Context() article, ok := ctx.Value("article").(*Article) if !ok { http.Error(w, http.StatusText(422), 422) return } w.Write([]byte(fmt.Sprintf("title:%s", article.Title)))}// A completely separate router for administrator routesfunc adminRouter() http.Handler { r := chi.NewRouter() r.Use(AdminOnly) r.Get("/", adminIndex) r.Get("/accounts", adminListAccounts) return r}func AdminOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() perm, ok := ctx.Value("acl.permission").(YourPermissionType) if !ok || !perm.IsAdmin() { http.Error(w, http.StatusText(403), 403) return } next.ServeHTTP(w, r) })}Router interface
chi's router is based on a kind ofPatricia Radix trie.The router is fully compatible withnet/http.
Built on top of the tree is theRouter interface:
// Router consisting of the core routing methods used by chi's Mux,// using only the standard net/http.type Router interface {http.HandlerRoutes// Use appends one or more middlewares onto the Router stack.Use(middlewares ...func(http.Handler) http.Handler)// With adds inline middlewares for an endpoint handler.With(middlewares ...func(http.Handler) http.Handler) Router// Group adds a new inline-Router along the current routing// path, with a fresh middleware stack for the inline-Router.Group(fn func(r Router)) Router// Route mounts a sub-Router along a `pattern` string.Route(pattern string, fn func(r Router)) Router// Mount attaches another http.Handler along ./pattern/*Mount(pattern string, h http.Handler)// Handle and HandleFunc adds routes for `pattern` that matches// all HTTP methods.Handle(pattern string, h http.Handler)HandleFunc(pattern string, h http.HandlerFunc)// Method and MethodFunc adds routes for `pattern` that matches// the `method` HTTP method.Method(method, pattern string, h http.Handler)MethodFunc(method, pattern string, h http.HandlerFunc)// HTTP-method routing along `pattern`Connect(pattern string, h http.HandlerFunc)Delete(pattern string, h http.HandlerFunc)Get(pattern string, h http.HandlerFunc)Head(pattern string, h http.HandlerFunc)Options(pattern string, h http.HandlerFunc)Patch(pattern string, h http.HandlerFunc)Post(pattern string, h http.HandlerFunc)Put(pattern string, h http.HandlerFunc)Trace(pattern string, h http.HandlerFunc)// NotFound defines a handler to respond whenever a route could// not be found.NotFound(h http.HandlerFunc)// MethodNotAllowed defines a handler to respond whenever a method is// not allowed.MethodNotAllowed(h http.HandlerFunc)}// Routes interface adds two methods for router traversal, which is also// used by the github.com/go-chi/docgen package to generate documentation for Routers.type Routes interface {// Routes returns the routing tree in an easily traversable structure.Routes() []Route// Middlewares returns the list of middlewares in use by the router.Middlewares() Middlewares// Match searches the routing tree for a handler that matches// the method/path - similar to routing a http request, but without// executing the handler thereafter.Match(rctx *Context, method, path string) bool}Each routing method accepts a URLpattern and chain ofhandlers. The URL patternsupports named params (ie./users/{userID}) and wildcards (ie./admin/*). URL parameterscan be fetched at runtime by callingchi.URLParam(r, "userID") for named parametersandchi.URLParam(r, "*") for a wildcard parameter.
Middleware handlers
chi's middlewares are just stdlib net/http middleware handlers. There is nothing specialabout them, which means the router and all the tooling is designed to be compatible andfriendly with any middleware in the community. This offers much better extensibility and reuseof packages and is at the heart of chi's purpose.
Here is an example of a standard net/http middleware where we assign a context key"user"the value of"123". This middleware sets a hypothetical user identifier on the requestcontext and calls the next handler in the chain.
// HTTP middleware setting a value on the request contextfunc MyMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // create new context from `r` request context, and assign key `"user"` // to value of `"123"` ctx := context.WithValue(r.Context(), "user", "123") // call the next handler in the chain, passing the response writer and // the updated request object with the new context value. // // note: context.Context values are nested, so any previously set // values will be accessible as well, and the new `"user"` key // will be accessible from this point forward. next.ServeHTTP(w, r.WithContext(ctx)) })}Request handlers
chi uses standard net/http request handlers. This little snippet is an example of a http.Handlerfunc that reads a user identifier from the request context - hypothetically, identifyingthe user sending an authenticated request, validated+set by a previous middleware handler.
// HTTP handler accessing data from the request context.func MyRequestHandler(w http.ResponseWriter, r *http.Request) { // here we read from the request context and fetch out `"user"` key set in // the MyMiddleware example above. user := r.Context().Value("user").(string) // respond to the client w.Write([]byte(fmt.Sprintf("hi %s", user)))}URL parameters
chi's router parses and stores URL parameters right onto the request context. Here isan example of how to access URL params in your net/http handlers. And of course, middlewaresare able to access the same information.
// HTTP handler accessing the url routing parameters.func MyRequestHandler(w http.ResponseWriter, r *http.Request) { // fetch the url parameter `"userID"` from the request of a matching // routing pattern. An example routing pattern could be: /users/{userID} userID := chi.URLParam(r, "userID") // fetch `"key"` from the request context ctx := r.Context() key := ctx.Value("key").(string) // respond to the client w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))}Middlewares
chi comes equipped with an optionalmiddleware package, providing a suite of standardnet/http middlewares. Please note, any middleware in the ecosystem that is also compatiblewithnet/http can be used with chi's mux.
Core middlewares
| chi/middleware Handler | description |
|---|---|
| AllowContentEncoding | Enforces a whitelist of request Content-Encoding headers |
| AllowContentType | Explicit whitelist of accepted request Content-Types |
| BasicAuth | Basic HTTP authentication |
| Compress | Gzip compression for clients that accept compressed responses |
| ContentCharset | Ensure charset for Content-Type request headers |
| CleanPath | Clean double slashes from request path |
| GetHead | Automatically route undefined HEAD requests to GET handlers |
| Heartbeat | Monitoring endpoint to check the servers pulse |
| Logger | Logs the start and end of each request with the elapsed processing time |
| NoCache | Sets response headers to prevent clients from caching |
| Profiler | Easily attach net/http/pprof to your routers |
| RealIP | Sets a http.Request's RemoteAddr to either X-Real-IP or X-Forwarded-For |
| Recoverer | Gracefully absorb panics and prints the stack trace |
| RequestID | Injects a request ID into the context of each request |
| RedirectSlashes | Redirect slashes on routing paths |
| RouteHeaders | Route handling for request headers |
| SetHeader | Short-hand middleware to set a response header key/value |
| StripSlashes | Strip slashes on routing paths |
| Sunset | Sunset set Deprecation/Sunset header to response |
| Throttle | Puts a ceiling on the number of concurrent requests |
| Timeout | Signals to the request context when the timeout deadline is reached |
| URLFormat | Parse extension from url and put it on request context |
| WithValue | Short-hand middleware to set a key/value on the request context |
Extra middlewares & packages
Please seehttps://github.com/go-chi for additional packages.
| package | description |
|---|---|
| cors | Cross-origin resource sharing (CORS) |
| docgen | Print chi.Router routes at runtime |
| jwtauth | JWT authentication |
| hostrouter | Domain/host based request routing |
| httplog | Small but powerful structured HTTP request logging |
| httprate | HTTP request rate limiter |
| httptracer | HTTP request performance tracing library |
| httpvcr | Write deterministic tests for external sources |
| stampede | HTTP request coalescer |
context?
context is a tiny pkg that provides simple interface to signal context across call stacksand goroutines. It was originally written bySameer Ajmaniand is available in stdlib since go1.7.
Learn more athttps://blog.golang.org/context
and..
Benchmarks
The benchmark suite:https://github.com/pkieltyka/go-http-routing-benchmark
Results as of Nov 29, 2020 with Go 1.15.5 on Linux AMD 3950x
BenchmarkChi_Param 3075895 384 ns/op 400 B/op 2 allocs/opBenchmarkChi_Param5 2116603 566 ns/op 400 B/op 2 allocs/opBenchmarkChi_Param20 964117 1227 ns/op 400 B/op 2 allocs/opBenchmarkChi_ParamWrite 2863413 420 ns/op 400 B/op 2 allocs/opBenchmarkChi_GithubStatic 3045488 395 ns/op 400 B/op 2 allocs/opBenchmarkChi_GithubParam 2204115 540 ns/op 400 B/op 2 allocs/opBenchmarkChi_GithubAll 10000 113811 ns/op 81203 B/op 406 allocs/opBenchmarkChi_GPlusStatic 3337485 359 ns/op 400 B/op 2 allocs/opBenchmarkChi_GPlusParam 2825853 423 ns/op 400 B/op 2 allocs/opBenchmarkChi_GPlus2Params 2471697 483 ns/op 400 B/op 2 allocs/opBenchmarkChi_GPlusAll 194220 5950 ns/op 5200 B/op 26 allocs/opBenchmarkChi_ParseStatic 3365324 356 ns/op 400 B/op 2 allocs/opBenchmarkChi_ParseParam 2976614 404 ns/op 400 B/op 2 allocs/opBenchmarkChi_Parse2Params 2638084 439 ns/op 400 B/op 2 allocs/opBenchmarkChi_ParseAll 109567 11295 ns/op 10400 B/op 52 allocs/opBenchmarkChi_StaticAll 16846 71308 ns/op 62802 B/op 314 allocs/opComparison with other routers:https://gist.github.com/pkieltyka/123032f12052520aaccab752bd3e78cc
NOTE: the allocs in the benchmark above are from the calls to http.Request'sWithContext(context.Context) method that clones the http.Request, sets theContext()on the duplicated (alloc'd) request and returns it the new request object. This is justhow setting context on a request in Go works.
Credits
- Carl Jackson forhttps://github.com/zenazn/goji
- Armon Dadgar forhttps://github.com/armon/go-radix
- Contributions:@VojtechVitek
We'll be more than happy to seeyour contributions!
Beyond REST
chi is just a http router that lets you decompose request handling into many smaller layers.Many companies use chi to write REST services for their public APIs. But, REST is just a conventionfor managing state via HTTP, and there's a lot of other pieces required to write a complete client-serversystem or network of microservices.
Looking beyond REST, I also recommend some newer works in the field:
- webrpc - Web-focused RPC client+server framework with code-gen
- gRPC - Google's RPC framework via protobufs
- graphql - Declarative query language
- NATS - lightweight pub-sub
License
Copyright (c) 2015-presentPeter Kieltyka
Licensed underMIT License
Documentation¶
Overview¶
Package chi is a small, idiomatic and composable router for building HTTP services.
chi requires Go 1.14 or newer.
Example:
package mainimport ("net/http""github.com/go-chi/chi/v5""github.com/go-chi/chi/v5/middleware")func main() {r := chi.NewRouter()r.Use(middleware.Logger)r.Use(middleware.Recoverer)r.Get("/", func(w http.ResponseWriter, r *http.Request) {w.Write([]byte("root."))})http.ListenAndServe(":3333", r)}See github.com/go-chi/chi/_examples/ for more in-depth examples.
URL patterns allow for easy matching of path components in HTTPrequests. The matching components can then be accessed usingchi.URLParam(). All patterns must begin with a slash.
A simple named placeholder {name} matches any sequence of charactersup to the next / or the end of the URL. Trailing slashes on paths mustbe handled explicitly.
A placeholder with a name followed by a colon allows a regularexpression match, for example {number:\\d+}. The regular expressionsyntax is Go's normal regexp RE2 syntax, except that / will never bematched. An anonymous regexp pattern is allowed, using an empty stringbefore the colon in the placeholder, such as {:\\d+}
The special placeholder of asterisk matches the rest of the requestedURL. Any trailing characters in the pattern are ignored. This is the onlyplaceholder which will match / characters.
Examples:
"/user/{name}" matches "/user/jsmith" but not "/user/jsmith/info" or "/user/jsmith/""/user/{name}/info" matches "/user/jsmith/info""/page/*" matches "/page/intro/latest""/page/{other}/latest" also matches "/page/intro/latest""/date/{yyyy:\\d\\d\\d\\d}/{mm:\\d\\d}/{dd:\\d\\d}" matches "/date/2017/04/01"Index¶
- Variables
- func RegisterMethod(method string)
- func URLParam(r *http.Request, key string) string
- func URLParamFromCtx(ctx context.Context, key string) string
- func Walk(r Routes, walkFn WalkFunc) error
- type ChainHandler
- type Context
- type Middlewares
- type Mux
- func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Find(rctx *Context, method, path string) string
- func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Group(fn func(r Router)) Router
- func (mx *Mux) Handle(pattern string, handler http.Handler)
- func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Match(rctx *Context, method, path string) bool
- func (mx *Mux) Method(method, pattern string, handler http.Handler)
- func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc)
- func (mx *Mux) MethodNotAllowedHandler(methodsAllowed ...methodTyp) http.HandlerFunc
- func (mx *Mux) Middlewares() Middlewares
- func (mx *Mux) Mount(pattern string, handler http.Handler)
- func (mx *Mux) NotFound(handlerFn http.HandlerFunc)
- func (mx *Mux) NotFoundHandler() http.HandlerFunc
- func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Route(pattern string, fn func(r Router)) Router
- func (mx *Mux) Routes() []Route
- func (mx *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler)
- func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router
- type Route
- type RouteParams
- type Router
- type Routes
- type WalkFunc
Constants¶
This section is empty.
Variables¶
var (// RouteCtxKey is the context.Context key to store the request context.RouteCtxKey = &contextKey{"RouteContext"})Functions¶
funcRegisterMethod¶
func RegisterMethod(methodstring)
RegisterMethod adds support for custom HTTP method handlers, availablevia Router#Method and Router#MethodFunc
funcURLParamFromCtx¶
URLParamFromCtx returns the url parameter from a http.Request Context.
Types¶
typeChainHandler¶
type ChainHandler struct {Endpointhttp.HandlerMiddlewaresMiddlewares// contains filtered or unexported fields}ChainHandler is a http.Handler with support for handler composition andexecution.
func (*ChainHandler)ServeHTTP¶
func (c *ChainHandler) ServeHTTP(whttp.ResponseWriter, r *http.Request)
typeContext¶
type Context struct {RoutesRoutes// Routing path/method override used during the route search.// See Mux#routeHTTP method.RoutePathstringRouteMethodstring// URLParams are the stack of routeParams captured during the// routing lifecycle across a stack of sub-routers.URLParamsRouteParams// Routing pattern stack throughout the lifecycle of the request,// across all connected routers. It is a record of all matching// patterns across a stack of sub-routers.RoutePatterns []string// contains filtered or unexported fields}Context is the default routing context set on the root node of arequest context to track route patterns, URL parameters andan optional routing path.
funcNewRouteContext¶
func NewRouteContext() *Context
NewRouteContext returns a new routing Context object.
funcRouteContext¶
RouteContext returns chi's routing Context object from ahttp.Request Context.
func (*Context)RoutePattern¶
RoutePattern builds the routing pattern string for the particularrequest, at the particular point during routing. This means, the valuewill change throughout the execution of a request in a router. That iswhy it's advised to only use this value after calling the next handler.
For example,
func Instrument(next http.Handler) http.Handler {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {next.ServeHTTP(w, r)routePattern := chi.RouteContext(r.Context()).RoutePattern()measure(w, r, routePattern)})}typeMiddlewares¶
Middlewares type is a slice of standard middleware handlers with methodsto compose middleware chains and http.Handler's.
funcChain¶
func Chain(middlewares ...func(http.Handler)http.Handler)Middlewares
Chain returns a Middlewares type from a slice of middleware handlers.
func (Middlewares)Handler¶
func (mwsMiddlewares) Handler(hhttp.Handler)http.Handler
Handler builds and returns a http.Handler from the chain of middlewares,with `h http.Handler` as the final handler.
func (Middlewares)HandlerFunc¶
func (mwsMiddlewares) HandlerFunc(hhttp.HandlerFunc)http.Handler
HandlerFunc builds and returns a http.Handler from the chain of middlewares,with `h http.Handler` as the final handler.
typeMux¶
type Mux struct {// contains filtered or unexported fields}Mux is a simple HTTP route multiplexer that parses a request path,records any URL params, and executes an end handler. It implementsthe http.Handler interface and is friendly with the standard library.
Mux is designed to be fast, minimal and offer a powerful API for buildingmodular and composable HTTP services with a large set of handlers. It'sparticularly useful for writing large REST API services that break a handlerinto many smaller parts composed of middlewares and end handlers.
funcNewMux¶
func NewMux() *Mux
NewMux returns a newly initialized Mux object that implements the Routerinterface.
funcNewRouter¶
func NewRouter() *Mux
NewRouter returns a new Mux object that implements the Router interface.
func (*Mux)Connect¶
func (mx *Mux) Connect(patternstring, handlerFnhttp.HandlerFunc)
Connect adds the route `pattern` that matches a CONNECT http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Delete¶
func (mx *Mux) Delete(patternstring, handlerFnhttp.HandlerFunc)
Delete adds the route `pattern` that matches a DELETE http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Find¶added inv5.2.0
Find searches the routing tree for the pattern that matchesthe method/path.
Note: the *Context state is updated during execution, so managethe state carefully or make a NewRouteContext().
func (*Mux)Get¶
func (mx *Mux) Get(patternstring, handlerFnhttp.HandlerFunc)
Get adds the route `pattern` that matches a GET http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Group¶
Group creates a new inline-Mux with a copy of middleware stack. It's usefulfor a group of handlers along the same routing path that use an additionalset of middlewares. See _examples/.
func (*Mux)Handle¶
Handle adds the route `pattern` that matches any http method toexecute the `handler` http.Handler.
func (*Mux)HandleFunc¶
func (mx *Mux) HandleFunc(patternstring, handlerFnhttp.HandlerFunc)
HandleFunc adds the route `pattern` that matches any http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Head¶
func (mx *Mux) Head(patternstring, handlerFnhttp.HandlerFunc)
Head adds the route `pattern` that matches a HEAD http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Match¶
Match searches the routing tree for a handler that matches the method/path.It's similar to routing a http request, but without executing the handlerthereafter.
Note: the *Context state is updated during execution, so managethe state carefully or make a NewRouteContext().
func (*Mux)Method¶
Method adds the route `pattern` that matches `method` http method toexecute the `handler` http.Handler.
func (*Mux)MethodFunc¶
func (mx *Mux) MethodFunc(method, patternstring, handlerFnhttp.HandlerFunc)
MethodFunc adds the route `pattern` that matches `method` http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)MethodNotAllowed¶
func (mx *Mux) MethodNotAllowed(handlerFnhttp.HandlerFunc)
MethodNotAllowed sets a custom http.HandlerFunc for routing paths where themethod is unresolved. The default handler returns a 405 with an empty body.
func (*Mux)MethodNotAllowedHandler¶
func (mx *Mux) MethodNotAllowedHandler(methodsAllowed ...methodTyp)http.HandlerFunc
MethodNotAllowedHandler returns the default Mux 405 responder whenevera method cannot be resolved for a route.
func (*Mux)Middlewares¶
func (mx *Mux) Middlewares()Middlewares
Middlewares returns a slice of middleware handler functions.
func (*Mux)Mount¶
Mount attaches another http.Handler or chi Router as a subrouter along a routingpath. It's very useful to split up a large API as many independent routers andcompose them as a single service using Mount. See _examples/.
Note that Mount() simply sets a wildcard along the `pattern` that will continuerouting at the `handler`, which in most cases is another chi.Router. As a result,if you define two Mount() routes on the exact same pattern the mount will panic.
func (*Mux)NotFound¶
func (mx *Mux) NotFound(handlerFnhttp.HandlerFunc)
NotFound sets a custom http.HandlerFunc for routing paths that couldnot be found. The default 404 handler is `http.NotFound`.
func (*Mux)NotFoundHandler¶
func (mx *Mux) NotFoundHandler()http.HandlerFunc
NotFoundHandler returns the default Mux 404 responder whenever a routecannot be found.
func (*Mux)Options¶
func (mx *Mux) Options(patternstring, handlerFnhttp.HandlerFunc)
Options adds the route `pattern` that matches an OPTIONS http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Patch¶
func (mx *Mux) Patch(patternstring, handlerFnhttp.HandlerFunc)
Patch adds the route `pattern` that matches a PATCH http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Post¶
func (mx *Mux) Post(patternstring, handlerFnhttp.HandlerFunc)
Post adds the route `pattern` that matches a POST http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Put¶
func (mx *Mux) Put(patternstring, handlerFnhttp.HandlerFunc)
Put adds the route `pattern` that matches a PUT http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Route¶
Route creates a new Mux and mounts it along the `pattern` as a subrouter.Effectively, this is a short-hand call to Mount. See _examples/.
func (*Mux)Routes¶
Routes returns a slice of routing information from the tree,useful for traversing available routes of a router.
func (*Mux)ServeHTTP¶
func (mx *Mux) ServeHTTP(whttp.ResponseWriter, r *http.Request)
ServeHTTP is the single method of the http.Handler interface that makesMux interoperable with the standard library. It uses a sync.Pool to get andreuse routing contexts for each request.
func (*Mux)Trace¶
func (mx *Mux) Trace(patternstring, handlerFnhttp.HandlerFunc)
Trace adds the route `pattern` that matches a TRACE http method toexecute the `handlerFn` http.HandlerFunc.
func (*Mux)Use¶
Use appends a middleware handler to the Mux middleware stack.
The middleware stack for any Mux will execute before searching for a matchingroute to a specific handler, which provides opportunity to respond early,change the course of the request execution, or set request-scoped values forthe next http.Handler.
typeRouteParams¶
type RouteParams struct {Keys, Values []string}RouteParams is a structure to track URL routing parameters efficiently.
func (*RouteParams)Add¶
func (s *RouteParams) Add(key, valuestring)
Add will append a URL parameter to the end of the route param
typeRouter¶
type Router interface {http.HandlerRoutes// Use appends one or more middlewares onto the Router stack.Use(middlewares ...func(http.Handler)http.Handler)// With adds inline middlewares for an endpoint handler.With(middlewares ...func(http.Handler)http.Handler)Router// Group adds a new inline-Router along the current routing// path, with a fresh middleware stack for the inline-Router.Group(fn func(rRouter))Router// Route mounts a sub-Router along a `pattern“ string.Route(patternstring, fn func(rRouter))Router// Mount attaches another http.Handler along ./pattern/*Mount(patternstring, hhttp.Handler)// Handle and HandleFunc adds routes for `pattern` that matches// all HTTP methods.Handle(patternstring, hhttp.Handler)HandleFunc(patternstring, hhttp.HandlerFunc)// Method and MethodFunc adds routes for `pattern` that matches// the `method` HTTP method.Method(method, patternstring, hhttp.Handler)MethodFunc(method, patternstring, hhttp.HandlerFunc)// HTTP-method routing along `pattern`Connect(patternstring, hhttp.HandlerFunc)Delete(patternstring, hhttp.HandlerFunc)Get(patternstring, hhttp.HandlerFunc)Head(patternstring, hhttp.HandlerFunc)Options(patternstring, hhttp.HandlerFunc)Patch(patternstring, hhttp.HandlerFunc)Post(patternstring, hhttp.HandlerFunc)Put(patternstring, hhttp.HandlerFunc)Trace(patternstring, hhttp.HandlerFunc)// NotFound defines a handler to respond whenever a route could// not be found.NotFound(hhttp.HandlerFunc)// MethodNotAllowed defines a handler to respond whenever a method is// not allowed.MethodNotAllowed(hhttp.HandlerFunc)}Router consisting of the core routing methods used by chi's Mux,using only the standard net/http.
typeRoutes¶
type Routes interface {// Routes returns the routing tree in an easily traversable structure.Routes() []Route// Middlewares returns the list of middlewares in use by the router.Middlewares()Middlewares// Match searches the routing tree for a handler that matches// the method/path - similar to routing a http request, but without// executing the handler thereafter.Match(rctx *Context, method, pathstring)bool// Find searches the routing tree for the pattern that matches// the method/path.Find(rctx *Context, method, pathstring)string}Routes interface adds two methods for router traversal, which is alsoused by the `docgen` subpackage to generation documentation for Routers.
Directories¶
| Path | Synopsis |
|---|---|
_examples | |
custom-handlercommand | |
custom-methodcommand | |
fileservercommand This example demonstrates how to serve static files from your filesystem. | This example demonstrates how to serve static files from your filesystem. |
gracefulcommand | |
hello-worldcommand | |
limitscommand This example demonstrates the use of Timeout, and Throttle middlewares. | This example demonstrates the use of Timeout, and Throttle middlewares. |
loggingcommand | |
pathvaluecommand | |
router-walkcommand | |
todos-resourcecommand This example demonstrates a project structure that defines a subrouter and its handlers on a struct, and mounting them as subrouters to a parent router. | This example demonstrates a project structure that defines a subrouter and its handlers on a struct, and mounting them as subrouters to a parent router. |