chi

package module
v0.0.0-...-771431e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 27, 2018 License: MIT Imports: 10 Imported by: 0

README

chi

GoDoc Widget Travis Widget

chi is a lightweight, idiomatic and composable router for building Go 1.7+ HTTP services. It's especially good at helping you write large REST API services that are kept maintainable as your project grows and changes. chi is built on the new context package introduced in Go 1.7 to handle 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 writing REST API servers, written during the development of the Pressly API service that powers our public API service, which in turn powers all of our client-side applications.

The key considerations of chi's design are: project structure, maintainability, standard http handlers (stdlib-only), developer productivity, and deconstructing a large system into many small parts. The core router github.com/go-chi/chi is quite small (less than 1000 LOC), but we've also included some useful/optional subpackages: middleware, render and docgen. We hope you enjoy it too!

Install

go get -u github.com/go-chi/chi

Features

  • Lightweight - cloc'd in ~1000 LOC for the chi router
  • Fast - yes, see benchmarks
  • 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 subrouter mounting
  • Context control - built on new context package, providing value chaining, cancelations and timeouts
  • Robust - in production at Pressly, CloudFlare, Heroku, 99Designs, and many others (see discussion)
  • Doc generation - docgen auto-generates routing documentation from your source to JSON or Markdown
  • No external dependencies - plain ol' Go 1.7+ stdlib + net/http

Examples

  • rest - REST APIs made easy, productive and maintainable
  • logging - Easy structured logging for any backend
  • limits - Timeouts and Throttling
  • todos-resource - Struct routers/handlers, an example of another code layout style
  • versions - Demo of chi/render subpkg
  • fileserver - Easily serve static files
  • graceful - Graceful context signaling and server shutdown

As easy as:

package main

import (
	"net/http"
	"github.com/go-chi/chi"
)

func main() {
	r := chi.NewRouter()
	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 how routing looks like with chi. Also take a look at the generated routing docs in JSON (routes.json) and in Markdown (routes.md).

I highly recommend reading the source of the examples listed above, they will show you all the features of chi and serve as a good form of documentation.

import (
  //...
  "context"
  "github.com/go-chi/chi"
  "github.com/go-chi/chi/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 routes
func 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 design

chi's router is based on a kind of Patricia Radix trie. The router is fully compatible with net/http.

Built on top of the tree is the Router interface:

// Router consisting of the core routing methods used by chi's Mux,
// using only the standard net/http.
type Router interface {
	http.Handler
	Routes

	// Use appends one of 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 URL pattern and chain of handlers. The URL pattern supports named params (ie. /users/{userID}) and wildcards (ie. /admin/*). URL parameters can be fetched at runtime by calling chi.URLParam(r, "userID") for named parameters and chi.URLParam(r, "*") for a wildcard parameter.

Middleware handlers

chi's middlewares are just stdlib net/http middleware handlers. There is nothing special about them, which means the router and all the tooling is designed to be compatible and friendly with any middleware in the community. This offers much better extensibility and reuse of packages and is at the heart of chi's purpose.

Here is an example of a standard net/http middleware handler using the new request context available in Go 1.7+. This middleware sets a hypothetical user identifier on the request context and calls the next handler in the chain.

// HTTP middleware setting a value on the request context
func MyMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    ctx := context.WithValue(r.Context(), "user", "123")
    next.ServeHTTP(w, r.WithContext(ctx))
  })
}
Request handlers

chi uses standard net/http request handlers. This little snippet is an example of a http.Handler func that reads a user identifier from the request context - hypothetically, identifying the 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) {
  user := r.Context().Value("user").(string)
  w.Write([]byte(fmt.Sprintf("hi %s", user)))
}
URL parameters

chi's router parses and stores URL parameters right onto the request context. Here is an example of how to access URL params in your net/http handlers. And of course, middlewares are able to access the same information.

// HTTP handler accessing the url routing parameters.
func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
  userID := chi.URLParam(r, "userID") // from a route like /users/{userID}

  ctx := r.Context()
  key := ctx.Value("key").(string)

  w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))
}

Middlewares

chi comes equipped with an optional middleware package, providing a suite of standard net/http middlewares. Please note, any middleware in the ecosystem that is also compatible with net/http can be used with chi's mux.

Core middlewares

chi/middleware Handler description
AllowContentType Explicit whitelist of accepted request Content-Types
Compress Gzip compression for clients that accept compressed responses
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-Forwarded-For or X-Real-IP
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
SetHeader Short-hand middleware to set a response header key/value
StripSlashes Strip slashes on routing paths
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

Auxiliary middlewares & packages

Please see https://github.com/go-chi for additional packages.


package description
cors Cross-origin resource sharing (CORS)
jwtauth JWT authentication
hostrouter Domain/host based request routing
httpcoala HTTP request coalescer
chi-authz Request ACL via https://github.com/hsluoyz/casbin
phi Port chi to fasthttp

please submit a PR if you'd like to include a link to a chi-compatible middleware

context?

context is a tiny pkg that provides simple interface to signal context across call stacks and goroutines. It was originally written by Sameer Ajmani and is available in stdlib since go1.7.

Learn more at https://blog.golang.org/context

and..

Benchmarks

The benchmark suite: https://github.com/pkieltyka/go-http-routing-benchmark

Results as of Aug 31, 2017 on Go 1.9.0

BenchmarkChi_Param        	 3000000	       607 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_Param5       	 2000000	       935 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_Param20      	 1000000	      1944 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_ParamWrite   	 2000000	       664 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_GithubStatic 	 2000000	       627 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_GithubParam  	 2000000	       847 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_GithubAll    	   10000	    175556 ns/op	   87700 B/op	     609 allocs/op
BenchmarkChi_GPlusStatic  	 3000000	       566 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_GPlusParam   	 2000000	       652 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_GPlus2Params 	 2000000	       767 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_GPlusAll     	  200000	      9794 ns/op	    5616 B/op	      39 allocs/op
BenchmarkChi_ParseStatic  	 3000000	       590 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_ParseParam   	 2000000	       656 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_Parse2Params 	 2000000	       715 ns/op	     432 B/op	       3 allocs/op
BenchmarkChi_ParseAll     	  100000	     18045 ns/op	   11232 B/op	      78 allocs/op
BenchmarkChi_StaticAll    	   10000	    108871 ns/op	   67827 B/op	     471 allocs/op

Comparison with other routers: https://gist.github.com/pkieltyka/c089f309abeb179cfc4deaa519956d8c

NOTE: the allocs in the benchmark above are from the calls to http.Request's WithContext(context.Context) method that clones the http.Request, sets the Context() on the duplicated (alloc'd) request and returns it the new request object. This is just how setting context on a request in Go 1.7+ works.

Credits

We'll be more than happy to see your contributions!

Beyond REST

chi is just a http router that lets you decompose request handling into many smaller layers. Many companies including Pressly.com (of course) use chi to write REST services for their public APIs. But, REST is just a convention for managing state via HTTP, and there's a lot of other pieces required to write a complete client-server system or network of microservices.

Looking ahead beyond REST, I also recommend some newer works in the field coming from gRPC, NATS, go-kit and even graphql. They're all pretty cool with their own unique approaches and benefits. Specifically, I'd look at gRPC since it makes client-server communication feel like a single program on a single computer, no need to hand-write a client library and the request/response payloads are typed contracts. NATS is pretty amazing too as a super fast and lightweight pub-sub transport that can speak protobufs, with nice service discovery - an excellent combination with gRPC.

License

Copyright (c) 2015-present Peter Kieltyka

Licensed under MIT License

Documentation

Overview

Package chi is a small, idiomatic and composable router for building HTTP services.

chi requires Go 1.7 or newer.

Example:

package main

import (
	"net/http"

	"github.com/go-chi/chi"
	"github.com/go-chi/chi/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 HTTP requests. The matching components can then be accessed using chi.URLParam(). All patterns must begin with a slash.

A simple named placeholder {name} matches any sequence of characters up to the next / or the end of the URL. Trailing slashes on paths must be handled explicitly.

A placeholder with a name followed by a colon allows a regular expression match, for example {number:\\d+}. The regular expression syntax is Go's normal regexp RE2 syntax, except that regular expressions including { or } are not supported, and / will never be matched. An anonymous regexp pattern is allowed, using an empty string before the colon in the placeholder, such as {:\\d+}

The special placeholder of asterisk matches the rest of the requested URL. Any trailing characters in the pattern are ignored. This is the only placeholder 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/*/index" also matches "/page/intro/latest"
"/date/{yyyy:\\d\\d\\d\\d}/{mm:\\d\\d}/{dd:\\d\\d}" matches "/date/2017/04/01"

Index

Constants

This section is empty.

Variables

View Source
var (
	// RouteCtxKey is the context.Context key to store the request context.
	RouteCtxKey = &contextKey{"RouteContext"}
)

Functions

func RegisterMethod

func RegisterMethod(method string)

RegisterMethod adds support for custom HTTP method handlers, available via Router#Method and Router#MethodFunc

func ServerBaseContext

func ServerBaseContext(baseCtx context.Context, h http.Handler) http.Handler

ServerBaseContext wraps an http.Handler to set the request context to the `baseCtx`.

func URLParam

func URLParam(r *http.Request, key string) string

URLParam returns the url parameter from a http.Request object.

func URLParamFromCtx

func URLParamFromCtx(ctx context.Context, key string) string

URLParamFromCtx returns the url parameter from a http.Request Context.

func Walk

func Walk(r Routes, walkFn WalkFunc) error

Walk walks any router tree that implements Routes interface.

Types

type ChainHandler

type ChainHandler struct {
	Middlewares Middlewares
	Endpoint    http.Handler
	// contains filtered or unexported fields
}

ChainHandler is a http.Handler with support for handler composition and execution.

func (*ChainHandler) ServeHTTP

func (c *ChainHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type Context

type Context struct {
	Routes Routes

	// Routing path/method override used during the route search.
	// See Mux#routeHTTP method.
	RoutePath   string
	RouteMethod string

	// 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

	// URLParams are the stack of routeParams captured during the
	// routing lifecycle across a stack of sub-routers.
	URLParams RouteParams
	// contains filtered or unexported fields
}

Context is the default routing context set on the root node of a request context to track route patterns, URL parameters and an optional routing path.

func NewRouteContext

func NewRouteContext() *Context

NewRouteContext returns a new routing Context object.

func RouteContext

func RouteContext(ctx context.Context) *Context

RouteContext returns chi's routing Context object from a http.Request Context.

func (*Context) Reset

func (x *Context) Reset()

Reset a routing context to its initial state.

func (*Context) RoutePattern

func (x *Context) RoutePattern() string

RoutePattern builds the routing pattern string for the particular request, at the particular point during routing. This means, the value will change throughout the execution of a request in a router. That is why its 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)
	 })
}

func (*Context) URLParam

func (x *Context) URLParam(key string) string

URLParam returns the corresponding URL parameter value from the request routing context.

type Middlewares

type Middlewares []func(http.Handler) http.Handler

Middlewares type is a slice of standard middleware handlers with methods to compose middleware chains and http.Handler's.

func Chain

func Chain(middlewares ...func(http.Handler) http.Handler) Middlewares

Chain returns a Middlewares type from a slice of middleware handlers.

func (Middlewares) Handler

func (mws Middlewares) Handler(h http.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 (mws Middlewares) HandlerFunc(h http.HandlerFunc) http.Handler

HandlerFunc builds and returns a http.Handler from the chain of middlewares, with `h http.Handler` as the final handler.

type Mux

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 implements the http.Handler interface and is friendly with the standard library.

Mux is designed to be fast, minimal and offer a powerful API for building modular and composable HTTP services with a large set of handlers. It's particularly useful for writing large REST API services that break a handler into many smaller parts composed of middlewares and end handlers.

func NewMux

func NewMux() *Mux

NewMux returns a newly initialized Mux object that implements the Router interface.

func NewRouter

func NewRouter() *Mux

NewRouter returns a new Mux object that implements the Router interface.

func (*Mux) Connect

func (mx *Mux) Connect(pattern string, handlerFn http.HandlerFunc)

Connect adds the route `pattern` that matches a CONNECT http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Delete

func (mx *Mux) Delete(pattern string, handlerFn http.HandlerFunc)

Delete adds the route `pattern` that matches a DELETE http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Get

func (mx *Mux) Get(pattern string, handlerFn http.HandlerFunc)

Get adds the route `pattern` that matches a GET http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Group

func (mx *Mux) Group(fn func(r Router)) Router

Group creates a new inline-Mux with a fresh middleware stack. It's useful for a group of handlers along the same routing path that use an additional set of middlewares. See _examples/.

func (*Mux) Handle

func (mx *Mux) Handle(pattern string, handler http.Handler)

Handle adds the route `pattern` that matches any http method to execute the `handler` http.Handler.

func (*Mux) HandleFunc

func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc)

HandleFunc adds the route `pattern` that matches any http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Head

func (mx *Mux) Head(pattern string, handlerFn http.HandlerFunc)

Head adds the route `pattern` that matches a HEAD http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Match

func (mx *Mux) Match(rctx *Context, method, path string) bool

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 handler thereafter.

Note: the *Context state is updated during execution, so manage the state carefully or make a NewRouteContext().

func (*Mux) Method

func (mx *Mux) Method(method, pattern string, handler http.Handler)

Method adds the route `pattern` that matches `method` http method to execute the `handler` http.Handler.

func (*Mux) MethodFunc

func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc)

MethodFunc adds the route `pattern` that matches `method` http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) MethodNotAllowed

func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc)

MethodNotAllowed sets a custom http.HandlerFunc for routing paths where the method is unresolved. The default handler returns a 405 with an empty body.

func (*Mux) MethodNotAllowedHandler

func (mx *Mux) MethodNotAllowedHandler() http.HandlerFunc

MethodNotAllowedHandler returns the default Mux 405 responder whenever a 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

func (mx *Mux) Mount(pattern string, handler http.Handler)

Mount attaches another http.Handler or chi Router as a subrouter along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Mount. See _examples/.

Note that Mount() simply sets a wildcard along the `pattern` that will continue routing 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(handlerFn http.HandlerFunc)

NotFound sets a custom http.HandlerFunc for routing paths that could not 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 route cannot be found.

func (*Mux) Options

func (mx *Mux) Options(pattern string, handlerFn http.HandlerFunc)

Options adds the route `pattern` that matches a OPTIONS http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Patch

func (mx *Mux) Patch(pattern string, handlerFn http.HandlerFunc)

Patch adds the route `pattern` that matches a PATCH http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Post

func (mx *Mux) Post(pattern string, handlerFn http.HandlerFunc)

Post adds the route `pattern` that matches a POST http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Put

func (mx *Mux) Put(pattern string, handlerFn http.HandlerFunc)

Put adds the route `pattern` that matches a PUT http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Route

func (mx *Mux) Route(pattern string, fn func(r Router)) Router

Route creates a new Mux with a fresh middleware stack and mounts it along the `pattern` as a subrouter. Effectively, this is a short-hand call to Mount. See _examples/.

func (*Mux) Routes

func (mx *Mux) Routes() []Route

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(w http.ResponseWriter, r *http.Request)

ServeHTTP is the single method of the http.Handler interface that makes Mux interoperable with the standard library. It uses a sync.Pool to get and reuse routing contexts for each request.

func (*Mux) Trace

func (mx *Mux) Trace(pattern string, handlerFn http.HandlerFunc)

Trace adds the route `pattern` that matches a TRACE http method to execute the `handlerFn` http.HandlerFunc.

func (*Mux) Use

func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler)

Use appends a middleware handler to the Mux middleware stack.

The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next http.Handler.

func (*Mux) With

func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router

With adds inline middlewares for an endpoint handler.

type Route

type Route struct {
	Pattern   string
	Handlers  map[string]http.Handler
	SubRoutes Routes
}

Route describes the details of a routing handler.

type RouteParams

type RouteParams struct {
	Keys, Values []string
}

RouteParams is a structure to track URL routing parameters efficiently.

func (*RouteParams) Add

func (s *RouteParams) Add(key, value string)

Add will append a URL parameter to the end of the route param

type Router

type Router interface {
	http.Handler
	Routes

	// Use appends one of 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)
}

Router consisting of the core routing methods used by chi's Mux, using only the standard net/http.

type Routes

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
}

Routes interface adds two methods for router traversal, which is also used by the `docgen` subpackage to generation documentation for Routers.

type WalkFunc

type WalkFunc func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error

WalkFunc is the type of the function called for each method and route visited by Walk.

Directories

Path Synopsis
_examples
limits
Limits ====== This example demonstrates the use of Timeout, CloseNotify, and Throttle middlewares.
Limits ====== This example demonstrates the use of Timeout, CloseNotify, and Throttle middlewares.
logging
Custom Structured Logger ======================== This example demonstrates how to use middleware.RequestLogger, middleware.LogFormatter and middleware.LogEntry to build a structured logger using the amazing sirupsen/logrus package as the logging backend.
Custom Structured Logger ======================== This example demonstrates how to use middleware.RequestLogger, middleware.LogFormatter and middleware.LogEntry to build a structured logger using the amazing sirupsen/logrus package as the logging backend.
rest
REST ==== This example demonstrates a HTTP REST web service with some fixture data.
REST ==== This example demonstrates a HTTP REST web service with some fixture data.
todos-resource
Todos Resource ============== 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.
Todos Resource ============== 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.
versions
Versions ======== This example demonstrates the use of the render subpackage, with a quick concept for how to support multiple api versions.
Versions ======== This example demonstrates the use of the render subpackage, with a quick concept for how to support multiple api versions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL