penguin

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 13, 2022 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

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

chi requires Go 1.10 or newer.

Example:

package main

import (
	"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 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 Data

func Data(w http.ResponseWriter, r *http.Request, status int, v []byte)

Data writes raw bytes to the response, setting the Content-Type as application/octet-stream.

func HTML

func HTML(w http.ResponseWriter, r *http.Request, status int, name string, v any) error

HTML writes a string to the response, setting the Content-Type as text/template.

func JSON

func JSON(w http.ResponseWriter, r *http.Request, status int, v any) error

JSON marshals 'v' to JSON, automatically escaping HTML and setting the Content-Type as application/json.

func NoContent

func NoContent(w http.ResponseWriter, r *http.Request)

NoContent returns a HTTP 204 "No Content" response.

func PureJSON

func PureJSON(w http.ResponseWriter, r *http.Request, status int, v any) error

PureJSON marshals 'v' to JSON, setting the Content-Type as application/json and without escaping HTML

func RegisterMethod

func RegisterMethod(method string)

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

func Text

func Text(w http.ResponseWriter, r *http.Request, status int, v string)

Text writes a string to the response, setting the Content-Type as text/plain.

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.

func XML

func XML(w http.ResponseWriter, r *http.Request, status int, v any) error

XML marshals 'v' to JSON, setting the Content-Type as application/xml. It will automatically prepend a generic XML header (see encoding/xml.Header) if one is not found in the first 100 bytes of 'v'.

Types

type ChainHandler

type ChainHandler struct {
	Endpoint http.Handler

	Middlewares Middlewares
	// 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 Engine#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

	HTMLEngine ExecuteTemplate
	// 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 Controller

type Controller interface {
	Router(r Router)
}

Controller represents a portion of functionality for a web application whereby middleware can be added only to the controller

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine 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.

Engine 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 New

func New() *Engine

New returns a newly initialized Engine object that implements the Router interface.

func (*Engine) Connect

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

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

func (*Engine) Controller

func (mx *Engine) Controller(pattern string, c Controller)

Controller is a shorthand for Router.Route("/pattern", (&HomeController{}).Router) and makes it clearer that a controller is being used at a glance

func (*Engine) Delete

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

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

func (*Engine) Get

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

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

func (*Engine) Group

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

Group creates a new inline-Engine 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 (*Engine) HTML

func (mx *Engine) HTML(handler ExecuteTemplate)

HTML takes an ExecuteTemplate interface to handle execution of templates.

func (*Engine) HTMLFs

func (mx *Engine) HTMLFs(fs fs.FS, patterns ...string)

HTMLFs is like Engine.HTMLGlob but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns (Note that most file names serve as glob patterns matching only themselves.) and will be injected into each request for use by HTML. If the templates fail to parse the method will panic.

func (*Engine) HTMLFsReloadable

func (mx *Engine) HTMLFsReloadable(reload bool, fs fs.FS, patterns ...string)

HTMLFsReloadable is like Engine.HTMLGlob but reads from the file system fs instead of the host operating system's file system. It accepts a list of glob patterns (Note that most file names serve as glob patterns matching only themselves.) and will be injected into each request for use by HTML. The templates will be reloaded and parsed on each request when reload is set to true. If the templates fail to parse the method will panic.

func (*Engine) HTMLGlob

func (mx *Engine) HTMLGlob(patterns ...string)

HTMLGlob parses the template definitions in the files identified by the patterns and calls Engine.Use with middleware that injects the templates for use by HTML. If the templates fail to parse the method will panic.

func (*Engine) HTMLGlobReloadable

func (mx *Engine) HTMLGlobReloadable(reload bool, patterns ...string)

HTMLGlobReloadable parses the template definitions in the files identified by the patterns and calls Engine.Use with middleware that injects the templates for use by HTML but will reload and parse the templates with each request if reload is set to true. If the templates fail to parse the method will panic.

func (*Engine) Handle

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

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

func (*Engine) HandleFunc

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

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

func (*Engine) Head

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

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

func (*Engine) Match

func (mx *Engine) 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 (*Engine) Method

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

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

func (*Engine) MethodFunc

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

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

func (*Engine) MethodNotAllowed

func (mx *Engine) 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 (*Engine) MethodNotAllowedHandler

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

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

func (*Engine) Middlewares

func (mx *Engine) Middlewares() Middlewares

Middlewares returns a slice of middleware handler functions.

func (*Engine) Mount

func (mx *Engine) 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 (*Engine) NotFound

func (mx *Engine) 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 (*Engine) NotFoundHandler

func (mx *Engine) NotFoundHandler() http.HandlerFunc

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

func (*Engine) Options

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

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

func (*Engine) Patch

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

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

func (*Engine) Post

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

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

func (*Engine) Put

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

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

func (*Engine) Route

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

Route creates a new Engine 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 (*Engine) Routes

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

Routes returns a slice of routing information from the tree, useful for traversing available routes of a router.

func (*Engine) ServeHTTP

func (mx *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

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

func (*Engine) Static added in v0.1.2

func (mx *Engine) Static(rootPath string)

Static adds a handler using http.FileSystem that serves HTTP requests with the contents of the file system rooted at rootPath.

func (*Engine) StaticFS added in v0.1.2

func (mx *Engine) StaticFS(fs fs.FS)

StaticFS adds a handler using http.FileSystem that serves HTTP requests with the contents of the file system rooted at rootPath. fs is converted to a FileSystem implementation, for use with the FileServer.

func (*Engine) Trace

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

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

func (*Engine) Use

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

Use appends a middleware handler to the Engine middleware stack.

The middleware stack for any Engine 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 (*Engine) With

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

With adds inline middlewares for an endpoint handler.

type ExecuteTemplate

type ExecuteTemplate interface {
	ExecuteTemplate(w io.Writer, name string, data any) error
}

func HTMLEngineFromCtx

func HTMLEngineFromCtx(ctx context.Context) ExecuteTemplate

HTMLEngineFromCtx returns the html engine from a http.Request Context.

type M

type M map[string]any

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 Route

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

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

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

	// Controller is a shorthand for Router.Route("/pattern", MyController{}.Router)
	// and makes it clearer that a controller is being used at a glance.
	Controller(pattern string, c Controller)

	// HTML takes an ExecuteTemplate interface to handle execution of templates.
	HTML(handler ExecuteTemplate)

	// HTMLGlob parses the template definitions in the files identified by the patterns and calls Engine.Use
	// with middleware that injects the templates for use by HTML. If the templates fail to parse the method will panic.
	HTMLGlob(pattern ...string)

	// HTMLGlobReloadable parses the template definitions in the files identified by the patterns and calls Engine.Use
	// with middleware that injects the templates for use by HTML but will reload and parse the templates with each
	// request if reload is set to true. If the templates fail to parse the method will panic.
	HTMLGlobReloadable(reload bool, pattern ...string)

	// HTMLFs is like Engine.HTML or Engine.HTMLGlob but reads from the file system fs instead of the host operating system's file system.
	// It accepts a list of glob patterns (Note that most file names serve as glob patterns matching only themselves.) and
	// will be injected into each request for use by HTML. If the templates fail to parse the method will panic.
	HTMLFs(fs fs.FS, patterns ...string)

	// HTMLFsReloadable is like Engine.HTML or Engine.HTMLGlob but reads from the file system fs instead of the host operating system's file system.
	// It accepts a list of glob patterns (Note that most file names serve as glob patterns matching only themselves.) and
	// will be injected into each request for use by HTML. The templates will be reloaded and parsed on each
	// request when reload is set to true. If the templates fail to parse the method will panic.
	HTMLFsReloadable(reload bool, fs fs.FS, patterns ...string)

	// Static adds a handler using http.FileSystem that serves HTTP requests with the contents of the file system rooted at rootPath.
	Static(rootPath string)

	// StaticFS adds a handler using http.FileSystem that serves HTTP requests with the contents of the file system rooted at rootPath.
	// fs is converted to a FileSystem implementation, for use with the FileServer.
	StaticFS(fs fs.FS)
}

Router consisting of the core routing methods used by chi's Engine, 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 S

type S []any

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