fchi

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2022 License: MIT Imports: 12 Imported by: 6

README

chi

Build Status Coverage Status GoDevDoc Code lines Comments

chi is a lightweight, idiomatic and composable router for building Go HTTP services. It's especially good at helping you write large REST API services 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!

This Fork

This fork changes chi implementation to work with github.com/valyala/fasthttp.

Install

go get -u github.com/swaggest/fchi

Features

  • Lightweight - cloc'd in ~1000 LOC for the chi router
  • Fast - yes, see benchmarks
  • Designed for modular/composable APIs - middlewares, inline middlewares, route groups and subrouter mounting
  • Context control - built on new context package, providing value chaining, cancellations 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
  • Go.mod support - as of v5, go.mod support (see CHANGELOG)
  • No external dependencies - plain ol' Go stdlib + net/http

Examples

See _examples/ for a variety of examples.

As easy as:

package main

import (
	"context"

	"github.com/swaggest/fchi"
	"github.com/swaggest/fchi/middleware"
	"github.com/valyala/fasthttp"
)

func main() {
	r := fchi.NewRouter()
	r.Use(middleware.NoCache)
	r.Get("/", fchi.HandlerFunc(func(ctx context.Context, rc *fasthttp.RequestCtx) {
		rc.Write([]byte("welcome"))
	}))
	fasthttp.ListenAndServe(":3000", fchi.RequestHandler(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/swaggest/fchi"
  "github.com/swaggest/fchi/middleware"
)

func main() {
  r := fchi.NewRouter()

  // A good base middleware stack
  r.Use(middleware.RequestID)
  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("/", fchi.HandlerFunc(func(ctx context.Context, rc *fasthttp.RequestCtx) {
    rc.Write([]byte("hi"))
  }))

  // RESTy routes for "articles" resource
  r.Route("/articles", func(r fchi.Router) {
    r.With(paginate).Get("/", fchi.HandlerFunc(listArticles))                           // GET /articles
    r.With(paginate).Get("/{month}-{day}-{year}", fchi.HandlerFunc(listArticlesByDate)) // GET /articles/01-16-2017

    r.Post("/", fchi.HandlerFunc(createArticle))                                        // POST /articles
    r.Get("/search", fchi.HandlerFunc(searchArticles))                                  // GET /articles/search

    // Regexp url parameters:
    r.Get("/{articleSlug:[a-z-]+}", fchi.HandlerFunc(getArticleBySlug))                // GET /articles/home-is-toronto

    // Subrouters:
    r.Route("/{articleID}", func(r fchi.Router) {
      r.Use(ArticleCtx)
      r.Get("/", fchi.HandlerFunc(getArticle))                                          // GET /articles/123
      r.Put("/", fchi.HandlerFunc(updateArticle))                                       // PUT /articles/123
      r.Delete("/", fchi.HandlerFunc(deleteArticle))                                    // DELETE /articles/123
    })
  })

  // Mount the admin sub-router
  r.Mount("/admin", adminRouter())

  fasthttp.ListenAndServe(":3333", fchi.RequestHandler(r))
}

func ArticleCtx(next fchi.Handler) fchi.Handler {
  return fchi.HandlerFunc(func(ctx context.Context, rc *fasthttp.RequestCtx) {
    articleID := fchi.URLParam(rc, "articleID")
    article, err := dbGetArticle(articleID)
    if err != nil {
      rc.Error(http.StatusText(404), 404)
      return
    }
    ctx = context.WithValue(ctx, "article", article)
    next.ServeHTTP(ctx, rc)
  })
}

func getArticle(ctx context.Context, rc *fasthttp.RequestCtx) {
  article, ok := ctx.Value("article").(*Article)
  if !ok {
    rc.Error(http.StatusText(422), 422)
    return
  }
  rc.Write([]byte(fmt.Sprintf("title:%s", article.Title)))
}

// A completely separate router for administrator routes
func adminRouter() fchi.Handler {
  r := chi.NewRouter()
  r.Use(AdminOnly)
  r.Get("/", fchi.HandlerFunc(adminIndex))
  r.Get("/accounts", fchi.HandlerFunc(adminListAccounts))
  return r
}

func AdminOnly(next fchi.Handler) fchi.Handler {
  return fchi.HandlerFunc(func(ctx context.Context, rc *fasthttp.RequestCtx) {
    perm, ok := ctx.Value("acl.permission").(YourPermissionType)
    if !ok || !perm.IsAdmin() {
      rc.Error(http.StatusText(403), 403)
      return
    }
    next.ServeHTTP(ctx, rc)
  })
}

Router interface

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

Built on top of the tree is the Router interface:

// Router consisting of the core routing methods used by chi's Mux.
type Router interface {
	fchi.Handler
	Routes

	// Use appends one or more middlewares onto the Router stack.
	Use(middlewares ...func(fchi.Handler) fchi.Handler)

	// With adds inline middlewares for an endpoint handler.
	With(middlewares ...func(fchi.Handler) fchi.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 fchi.Handler along ./pattern/*
	Mount(pattern string, h fchi.Handler)

	// Handle and HandleFunc adds routes for `pattern` that matches
	// all HTTP methods.
	Handle(pattern string, h fchi.Handler)

	// Method and MethodFunc adds routes for `pattern` that matches
	// the `method` HTTP method.
	Method(method, pattern string, h fchi.Handler)

	// HTTP-method routing along `pattern`
	Connect(pattern string, h fchi.HandlerFunc)
	Delete(pattern string, h fchi.HandlerFunc)
	Get(pattern string, h fchi.HandlerFunc)
	Head(pattern string, h fchi.HandlerFunc)
	Options(pattern string, h fchi.HandlerFunc)
	Patch(pattern string, h fchi.HandlerFunc)
	Post(pattern string, h fchi.HandlerFunc)
	Put(pattern string, h fchi.HandlerFunc)
	Trace(pattern string, h fchi.HandlerFunc)

	// NotFound defines a handler to respond whenever a route could
	// not be found.
	NotFound(h fchi.HandlerFunc)

	// MethodNotAllowed defines a handler to respond whenever a method is
	// not allowed.
	MethodNotAllowed(h fchi.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

Here is an example of a fasthttp middleware handler using the new request context available in Go. 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 fchi.Handler) fchi.Handler {
  return fchi.HandlerFunc(func(ctx context.Context, rc *fasthttp.RequestCtx) {
    // 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 request context
    // 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(ctx, rc)
  })
}
Request handlers

chi uses fasthttp request handlers. This little snippet is an example of a fchi.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(ctx context.Context, rc *fasthttp.RequestCtx) {
  // here we read from the request context and fetch out `"user"` key set in
  // the MyMiddleware example above.
  user := ctx.Value("user").(string)

  // respond to the client
  rc.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 fasthttp handlers. And of course, middlewares are able to access the same information.

// HTTP handler accessing the url routing parameters.
func MyRequestHandler(ctx context.Context, rc *fasthttp.RequestCtx) {
  // fetch the url parameter `"userID"` from the request of a matching
  // routing pattern. An example routing pattern could be: /users/{userID}
  userID := fchi.URLParam(rc, "userID") // from a route like /users/{userID}

  // fetch `"key"` from the request context
  key := ctx.Value("key").(string)

  // respond to the client
  rc.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))
}

Middlewares

chi comes equipped with an optional middleware package, providing a suite of fasthttp middlewares.

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
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 see https://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 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 Nov 29, 2020 with Go 1.15.5 on Linux AMD 3950x

BenchmarkChi_Param          	3075895	        384 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_Param5         	2116603	        566 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_Param20        	 964117	       1227 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_ParamWrite     	2863413	        420 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GithubStatic   	3045488	        395 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GithubParam    	2204115	        540 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GithubAll      	  10000	     113811 ns/op	    81203 B/op    406 allocs/op
BenchmarkChi_GPlusStatic    	3337485	        359 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GPlusParam     	2825853	        423 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GPlus2Params   	2471697	        483 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GPlusAll       	 194220	       5950 ns/op	     5200 B/op     26 allocs/op
BenchmarkChi_ParseStatic    	3365324	        356 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_ParseParam     	2976614	        404 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_Parse2Params   	2638084	        439 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_ParseAll       	 109567	      11295 ns/op	    10400 B/op     52 allocs/op
BenchmarkChi_StaticAll      	  16846	      71308 ns/op	    62802 B/op    314 allocs/op

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

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 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 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 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-present Peter Kieltyka

Licensed under MIT License

Documentation

Overview

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

fchi requires Go 1.11 or newer.

Example:

 package main

 import (
		"context"

 	"github.com/swaggest/fchi"
 	"github.com/swaggest/fchi/middleware"
		"github.com/valyala/fasthttp"
 )

 func main() {
 	r := chi.NewRouter()
 	r.Use(middleware.Recoverer)

 	r.Get("/", func(ctx context.Context, rc *fasthttp.RequestCtx) {
 		rc.Write([]byte("root."))
 	})

 	fasthttp.ListenAndServe(":3333", fchi.RequestHandler(r))
 }

See github.com/swaggest/fchi/_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

This section is empty.

Functions

func Error added in v1.1.0

func Error(rc *fasthttp.RequestCtx, error string, statusCode int)

Error replies to the request with the specified error message and HTTP code. It does not otherwise end the request; the caller should ensure no further writes are done to w. The error message should be plain text.

func RegisterMethod added in v1.0.1

func RegisterMethod(method string)

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

func RequestHandler added in v1.0.1

func RequestHandler(handler Handler) fasthttp.RequestHandler

RequestHandler makes fasthttp.RequestHandler function from Handler.

func URLParam

func URLParam(rc *fasthttp.RequestCtx, key string) string

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

func URLParamFromCtx added in v1.0.1

func URLParamFromCtx(rc *fasthttp.RequestCtx, key string) string

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

func Walk added in v1.0.1

func Walk(r Routes, walkFn WalkFunc) error

Walk walks any router tree that implements Routes interface.

Types

type ChainHandler added in v1.0.1

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

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

func (*ChainHandler) ServeHTTP added in v1.0.1

func (c *ChainHandler) ServeHTTP(ctx context.Context, rc *fasthttp.RequestCtx)

type Context

type Context struct {
	Routes Routes

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

	// URLParams are the stack of routeParams captured during the
	// routing lifecycle across a stack of sub-routers.
	URLParams RouteParams

	// 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 a request context to track route patterns, URL parameters and an optional routing path.

func NewRouteContext added in v1.0.1

func NewRouteContext() *Context

NewRouteContext returns a new routing Context object.

func RouteContext

func RouteContext(rc *fasthttp.RequestCtx) *Context

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

func (*Context) Reset added in v1.0.1

func (x *Context) Reset()

Reset a routing context to its initial state.

func (*Context) RoutePattern added in v1.0.1

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 Handler) Handler {
  return HandlerFunc(func(ctx context.Context, rc *fasthttp.RequestCtx) {
    next.ServeHTTP(ctx, rc)
    routePattern := fchi.RouteContext(rc).RoutePattern()
    measure(ctx, rc, routePattern)
	 })
}

func (*Context) URLParam added in v1.0.1

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

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

type Handler

type Handler interface {
	ServeHTTP(ctx context.Context, rc *fasthttp.RequestCtx)
}

Handler is a FastHTTP handler.

func Adapt added in v1.0.1

func Adapt(h http.Handler) Handler

Adapt makes Handler from http.Handler.

type HandlerFunc

type HandlerFunc func(ctx context.Context, rc *fasthttp.RequestCtx)

HandlerFunc implements Handler.

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(ctx context.Context, rc *fasthttp.RequestCtx)

ServeHTTP serves http request.

type Middlewares added in v1.0.1

type Middlewares []func(Handler) Handler

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

func Chain added in v1.0.1

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

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

func (Middlewares) Handler added in v1.0.1

func (mws Middlewares) Handler(h Handler) Handler

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

func (Middlewares) HandlerFunc added in v1.0.1

func (mws Middlewares) HandlerFunc(h HandlerFunc) Handler

HandlerFunc builds and returns a Handler from the chain of middlewares, with `h 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 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, handler Handler)

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

func (*Mux) Delete

func (mx *Mux) Delete(pattern string, handler Handler)

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

func (*Mux) Get

func (mx *Mux) Get(pattern string, handler Handler)

Get adds the route `pattern` that matches a GET http method to execute the `handlerFn` 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 Handler)

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

func (*Mux) Head

func (mx *Mux) Head(pattern string, handler Handler)

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

func (*Mux) Match added in v1.0.1

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 added in v1.0.1

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

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

func (*Mux) MethodNotAllowed added in v1.0.1

func (mx *Mux) MethodNotAllowed(handler Handler)

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

func (*Mux) MethodNotAllowedHandler added in v1.0.1

func (mx *Mux) MethodNotAllowedHandler() Handler

MethodNotAllowedHandler returns the default Mux 405 responder whenever a method cannot be resolved for a route.

func (*Mux) Middlewares added in v1.0.1

func (mx *Mux) Middlewares() Middlewares

Middlewares returns a slice of middleware handler functions.

func (*Mux) Mount

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

Mount attaches another 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(handler Handler)

NotFound sets a custom HandlerFunc for routing paths that could not be found. The default 404 handler is `http.NotFound`.

func (*Mux) NotFoundHandler added in v1.0.1

func (mx *Mux) NotFoundHandler() Handler

NotFoundHandler returns the default Mux 404 responder whenever a route cannot be found.

func (*Mux) Options

func (mx *Mux) Options(pattern string, handler Handler)

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

func (*Mux) Patch

func (mx *Mux) Patch(pattern string, handler Handler)

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

func (*Mux) Post

func (mx *Mux) Post(pattern string, handler Handler)

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

func (*Mux) Put

func (mx *Mux) Put(pattern string, handler Handler)

Put adds the route `pattern` that matches a PUT http method to execute the `handlerFn` 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 added in v1.0.1

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(ctx context.Context, rc *fasthttp.RequestCtx)

ServeHTTP is the single method of the 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, handler Handler)

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

func (*Mux) Use

func (mx *Mux) Use(middlewares ...func(Handler) 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 Handler.

func (*Mux) With added in v1.0.1

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

With adds inline middlewares for an endpoint handler.

type Route added in v1.0.1

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

Route describes the details of a routing handler. Handlers map key is an HTTP method

type RouteParams added in v1.0.1

type RouteParams struct {
	Keys, Values []string
}

RouteParams is a structure to track URL routing parameters efficiently.

func (*RouteParams) Add added in v1.0.1

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 {
	Handler
	Routes

	// Use appends one or more middlewares onto the Router stack.
	Use(middlewares ...func(Handler) Handler)

	// With adds inline middlewares for an endpoint handler.
	With(middlewares ...func(Handler) 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 Handler along ./pattern/*
	Mount(pattern string, h Handler)

	// Handle and HandleFunc adds routes for `pattern` that matches
	// all HTTP methods.
	Handle(pattern string, h Handler)

	// Method and MethodFunc adds routes for `pattern` that matches
	// the `method` HTTP method.
	Method(method, pattern string, h Handler)

	// HTTP-method routing along `pattern`
	Connect(pattern string, h Handler)
	Delete(pattern string, h Handler)
	Get(pattern string, h Handler)
	Head(pattern string, h Handler)
	Options(pattern string, h Handler)
	Patch(pattern string, h Handler)
	Post(pattern string, h Handler)
	Put(pattern string, h Handler)
	Trace(pattern string, h Handler)

	// NotFound defines a handler to respond whenever a route could
	// not be found.
	NotFound(h Handler)

	// MethodNotAllowed defines a handler to respond whenever a method is
	// not allowed.
	MethodNotAllowed(h Handler)
}

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

type Routes added in v1.0.1

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 TestServer added in v1.0.1

type TestServer struct {
	URL string
	// contains filtered or unexported fields
}

TestServer is a test server.

func NewTestServer added in v1.0.1

func NewTestServer(r Handler) *TestServer

NewTestServer spawns fasthttp server on an available localhost port.

func (*TestServer) Close added in v1.0.1

func (ts *TestServer) Close()

Close stops test server.

type WalkFunc added in v1.0.1

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

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

Directories

Path Synopsis
_examples
fileserver
FileServer =========== This example demonstrates how to serve static files from your filesystem.
FileServer =========== This example demonstrates how to serve static files from your filesystem.
limits
Limits ====== This example demonstrates the use of Timeout, and Throttle middlewares.
Limits ====== This example demonstrates the use of Timeout, 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.
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