Documentation ¶
Overview ¶
Package clover is a small, idiomatic and composable router for building HTTP services.
clover requires Go 1.14 or newer.
Example:
package main import ( "net/http" "github.com/goclover/clover" "github.com/goclover/clover/middleware" ) func main() { r := clover.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/goclover/clover/_examples/ for more in-depth examples.
URL patterns allow for easy matcloverng of path components in HTTP requests. The matcloverng components can then be accessed using clover.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/{other}/index" 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 Clover
- type Context
- type HandlerFunc
- type Middlewares
- type Mux
- func (mx *Mux) Group(fn func(r Router)) Router
- func (mx *Mux) Handle(pattern string, handler HandlerFunc)
- func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) HandleStd(pattern string, handler http.Handler)
- func (mx *Mux) Match(rctx *Context, method, path string) bool
- func (mx *Mux) Method(method, pattern string, handler HandlerFunc)
- func (mx *Mux) MethodFunc(method, pattern string, handlerFn http.HandlerFunc)
- func (mx *Mux) MethodNotAllowed(handlerFn http.HandlerFunc)
- func (mx *Mux) MethodNotAllowedHandler() http.HandlerFunc
- func (mx *Mux) MethodStd(method, pattern string, handler http.Handler)
- 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) 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) Use(middlewares ...func(http.Handler) http.Handler)
- func (mx *Mux) With(middlewares ...func(http.Handler) http.Handler) Router
- type Request
- 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 ¶
func RegisterMethod ¶
func RegisterMethod(method string)
RegisterMethod adds support for custom HTTP method handlers, available via Router#Method and Router#MethodFunc
func URLParamFromCtx ¶
URLParamFromCtx returns the url parameter from a http.Request Context.
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 Clover ¶
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 matcloverng // 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 ¶
func NewRouteContext() *Context
NewRouteContext returns a new routing Context object.
func RouteContext ¶
RouteContext returns clover's routing Context object from a http.Request Context.
func (*Context) RoutePattern ¶
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 := clover.RouteContext(r.Context()).RoutePattern() measure(w, r, routePattern) }) }
type HandlerFunc ¶
HandlerFunc type is a func implement of http.Handler
func (HandlerFunc) ServeHTTP ¶
func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP is the single method of the http.Handler interface that makes it work
type Middlewares ¶
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 (*Mux) Group ¶
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 HandlerFunc)
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) HandleStd ¶
HandleStd adds the route `pattern` that matches any http method to execute the `handler` http.Handler.
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 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 HandlerFunc)
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) MethodStd ¶
MethodStd adds the route `pattern` that matches `method` http method to execute the `handler` http.Handler.
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 clover 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 clover.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) Route ¶
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 ¶
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) Use ¶
Use appends a middleware handler to the Mux middleware stack.
The middleware stack for any Mux will execute before searcloverng for a matcloverng 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.
type Request ¶
type Request interface { // 原始的http请求 HTTPRequest() *http.Request // Path 获取请求的路径 // ?前面的那部分 Path() string //Request URI RequestURI() string // 客户端的地址,如 127.0.0.1:12345 RemoteAddr() string // 请求头信息 Header(name string) (value string, has bool) // 读取header字段 HeaderDefault(name string, defaultValue string) string // 获取原始的cookie Cookie(name string) (value *http.Cookie, has bool) // Query 获取get请求里的参数 // 如 xxx?a=v1&b=v2,可获取a、b的值 Query(name string) (value string, has bool) // QueryDefault 获取get请求里的参数,若name不存在,或者是为空字符串,会返回默认值 QueryDefault(name string, defaultValue string) string PostForm(name string) (value string, has bool) PostFormDefault(name string, defaultValue string) string Param(name string) (value string, has bool) ParamDefault(name string, defaultValue string) string JsonUnmarshal(dst interface{}) error Body() io.ReadCloser }
Request http server 请求信息
func NewRequest ¶
NewRequest 基于原生的request创建一个封装更多功能的request
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 HandleStd and HandleFunc adds routes for `pattern` that matches // all HTTP methods. Handle(pattern string, h HandlerFunc) HandleStd(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 HandlerFunc) MethodStd(method, pattern string, h http.Handler) MethodFunc(method, 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 clover'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.