Documentation ¶
Overview ¶
Package clevergo is a trie based high performance HTTP request router.
Index ¶
- Variables
- func CleanPath(p string) string
- type Application
- func (app *Application) Any(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Delete(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Get(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Group(path string, opts ...RouteGroupOption) Router
- func (app *Application) Handle(method, path string, handle Handle, opts ...RouteOption)
- func (app *Application) Handler(method, path string, handler http.Handler, opts ...RouteOption)
- func (app *Application) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)
- func (app *Application) Head(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Lookup(method, path string) (*Route, Params, bool)
- func (app *Application) Options(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Patch(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Post(path string, handle Handle, opts ...RouteOption)
- func (app *Application) Put(path string, handle Handle, opts ...RouteOption)
- func (app *Application) RouteURL(name string, args ...string) (*url.URL, error)
- func (app *Application) Run(address string) error
- func (app *Application) RunTLS(address, certFile, keyFile string) error
- func (app *Application) RunUnix(address string) error
- func (app *Application) Serve(ln net.Listener) (err error)
- func (app *Application) ServeFiles(path string, root http.FileSystem, opts ...RouteOption)
- func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (app *Application) Use(middlewares ...MiddlewareFunc)
- type Context
- func (c *Context) BasicAuth() (username, password string, ok bool)
- func (c *Context) Blob(code int, contentType string, bs []byte) (err error)
- func (c *Context) Context() context.Context
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) Decode(v interface{}) (err error)
- func (c *Context) DefaultQuery(key, defaultVlue string) string
- func (c *Context) Emit(code int, contentType string, body string) (err error)
- func (c *Context) Error(code int, msg string) error
- func (c *Context) FormValue(key string) string
- func (c *Context) GetHeader(name string) string
- func (c *Context) HTML(code int, html string) error
- func (c *Context) HTMLBlob(code int, bs []byte) error
- func (c *Context) Host() string
- func (c *Context) IsAJAX() bool
- func (c *Context) IsDelete() bool
- func (c *Context) IsGet() bool
- func (c *Context) IsMethod(method string) bool
- func (c *Context) IsOptions() bool
- func (c *Context) IsPatch() bool
- func (c *Context) IsPost() bool
- func (c *Context) IsPut() bool
- func (c *Context) JSON(code int, data interface{}) error
- func (c *Context) JSONBlob(code int, bs []byte) error
- func (c *Context) JSONP(code int, data interface{}) error
- func (c *Context) JSONPBlob(code int, bs []byte) error
- func (c *Context) JSONPCallback(code int, callback string, data interface{}) error
- func (c *Context) JSONPCallbackBlob(code int, callback string, bs []byte) (err error)
- func (c *Context) Logger() log.Logger
- func (c *Context) NotFound() error
- func (c *Context) PostFormValue(key string) string
- func (c *Context) QueryParam(key string) string
- func (c *Context) QueryParams() url.Values
- func (c *Context) QueryString() string
- func (c *Context) Redirect(code int, url string) error
- func (c *Context) Render(code int, name string, data interface{}, args ...string) (err error)
- func (c *Context) RouteURL(name string, args ...string) (*url.URL, error)
- func (c *Context) SendFile(filename string, r io.Reader) (err error)
- func (c *Context) ServeContent(name string, modtime time.Time, content io.ReadSeeker) error
- func (c *Context) ServeFile(name string) error
- func (c *Context) SetContentType(v string)
- func (c *Context) SetContentTypeHTML()
- func (c *Context) SetContentTypeJSON()
- func (c *Context) SetContentTypeText()
- func (c *Context) SetContentTypeXML()
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) String(code int, s string) error
- func (c *Context) StringBlob(code int, bs []byte) error
- func (c *Context) Stringf(code int, format string, a ...interface{}) error
- func (c *Context) Value(key interface{}) interface{}
- func (c *Context) WithValue(key, val interface{})
- func (c *Context) Write(data []byte) (int, error)
- func (c *Context) WriteHeader(code int)
- func (c *Context) WriteString(data string) (int, error)
- func (c *Context) XML(code int, data interface{}) error
- func (c *Context) XMLBlob(code int, bs []byte) error
- type Decoder
- type Error
- type Handle
- type LoggingOption
- type Map
- type MiddlewareFunc
- type PanicError
- type Param
- type Params
- type Renderer
- type Route
- type RouteGroup
- func (r *RouteGroup) Any(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Delete(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Get(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Group(path string, opts ...RouteGroupOption) Router
- func (r *RouteGroup) Handle(method, path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Handler(method, path string, handler http.Handler, opts ...RouteOption)
- func (r *RouteGroup) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)
- func (r *RouteGroup) Head(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Options(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Patch(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Post(path string, handle Handle, opts ...RouteOption)
- func (r *RouteGroup) Put(path string, handle Handle, opts ...RouteOption)
- type RouteGroupOption
- type RouteOption
- type Router
- type Skipper
- type StatusError
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrRendererNotRegister = errors.New("renderer not registered") ErrDecoderNotRegister = errors.New("decoder not registered") )
errors
var ( ErrNotFound = StatusError{http.StatusNotFound, errors.New(http.StatusText(http.StatusNotFound))} ErrMethodNotAllowed = StatusError{http.StatusMethodNotAllowed, errors.New(http.StatusText(http.StatusMethodNotAllowed))} )
Errors
Functions ¶
func CleanPath ¶
CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.
The following rules are applied iteratively until no further processing can be done:
- Replace multiple slashes with a single slash.
- Eliminate each . path name element (the current directory).
- Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
- Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.
If the result of this process is an empty string, "/" is returned
Types ¶
type Application ¶
type Application struct { Server *http.Server // Graceful shutdown timeout. ShutdownTimeout time.Duration // Graceful shutdown signals. ShutdownSignals []os.Signal // Enables automatic redirection if the current route can't be matched but a // handler for the path with (without) the trailing slash exists. // For example if /foo/ is requested but a route only exists for /foo, the // client is redirected to /foo with http status code 301 for Get requests // and 308 for all other request methods. RedirectTrailingSlash bool // If enabled, the router tries to fix the current request path, if no // handle is registered for it. // First superfluous path elements like ../ or // are removed. // Afterwards the router does a case-insensitive lookup of the cleaned path. // If a handle can be found for this route, the router makes a redirection // to the corrected path with status code 301 for Get requests and 308 for // all other request methods. // For example /FOO and /..//Foo could be redirected to /foo. // RedirectTrailingSlash is independent of this option. RedirectFixedPath bool // If enabled, the router checks if another method is allowed for the // current route, if the current request can not be routed. // If this is the case, the request is answered with 'Method Not Allowed' // and HTTP status code 405. // If no other Method is allowed, the request is delegated to the NotFound // handler. HandleMethodNotAllowed bool // If enabled, the router automatically replies to OPTIONS requests. // Custom OPTIONS handlers take priority over automatic replies. HandleOPTIONS bool // An optional http.Handler that is called on automatic OPTIONS requests. // The handler is only called if HandleOPTIONS is true and no OPTIONS // handler for the specific path was set. // The "Allowed" header is set before calling the handler. GlobalOPTIONS http.Handler // Configurable http.Handler which is called when no matching route is // found. If it is not set, http.NotFound is used. NotFound http.Handler // Configurable http.Handler which is called when a request // cannot be routed and HandleMethodNotAllowed is true. // If it is not set, http.Error with http.StatusMethodNotAllowed is used. // The "Allow" header with allowed request methods is set before the handler // is called. MethodNotAllowed http.Handler // If enabled, use the request.URL.RawPath instead of request.URL.Path. UseRawPath bool // Template Renderer. Renderer Renderer // Request input decoder. Decoder Decoder Logger log.Logger // contains filtered or unexported fields }
Application is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes
func New ¶
func New() *Application
New returns an application which enable recovery, error handler, server header and logging middleware by default.
func Pure ¶ added in v0.2.0
func Pure() *Application
Pure returns a new initialized application. Path auto-correction, including trailing slashes, is enabled by default.
func (*Application) Any ¶
func (app *Application) Any(path string, handle Handle, opts ...RouteOption)
Any implements Router.Any.
func (*Application) Delete ¶
func (app *Application) Delete(path string, handle Handle, opts ...RouteOption)
Delete implements Router.Delete.
func (*Application) Get ¶
func (app *Application) Get(path string, handle Handle, opts ...RouteOption)
Get implements Router.Get.
func (*Application) Group ¶
func (app *Application) Group(path string, opts ...RouteGroupOption) Router
Group implements Router.Group.
func (*Application) Handle ¶
func (app *Application) Handle(method, path string, handle Handle, opts ...RouteOption)
Handle implements Router.Handle.
func (*Application) Handler ¶
func (app *Application) Handler(method, path string, handler http.Handler, opts ...RouteOption)
Handler implements Router.Handler.
func (*Application) HandlerFunc ¶
func (app *Application) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)
HandlerFunc implements Router.HandlerFunc.
func (*Application) Head ¶
func (app *Application) Head(path string, handle Handle, opts ...RouteOption)
Head implements Router.Head.
func (*Application) Lookup ¶
func (app *Application) Lookup(method, path string) (*Route, Params, bool)
Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.
func (*Application) Options ¶
func (app *Application) Options(path string, handle Handle, opts ...RouteOption)
Options implements Router.Options.
func (*Application) Patch ¶
func (app *Application) Patch(path string, handle Handle, opts ...RouteOption)
Patch implements Router.Patch.
func (*Application) Post ¶
func (app *Application) Post(path string, handle Handle, opts ...RouteOption)
Post implements Router.Post.
func (*Application) Put ¶
func (app *Application) Put(path string, handle Handle, opts ...RouteOption)
Put implements Router.Put.
func (*Application) RouteURL ¶
RouteURL creates an url with the given route name and arguments.
Example ¶
app := Pure() app.Get("/hello/:name", func(c *Context) error { return nil }, RouteName("hello")) // nested routes group api := app.Group("/api") v1 := api.Group("/v1") // the group path will become the prefix of route name. v1.Get("/users/:name", func(c *Context) error { return nil }, RouteName("user")) // specified the name of the route group. v2 := api.Group("/v2", RouteGroupName("/apiV2")) v2.Get("/users/:name", func(c *Context) error { return nil }, RouteName("user")) routes := []struct { name string args []string }{ {"hello", []string{"name", "foo"}}, {"hello", []string{"name", "bar"}}, {"/api/v1/user", []string{"name", "foo"}}, {"/api/v1/user", []string{"name", "bar"}}, {"/apiV2/user", []string{"name", "foo"}}, {"/apiV2/user", []string{"name", "bar"}}, } for _, route := range routes { url, _ := app.RouteURL(route.name, route.args...) fmt.Println(url) }
Output: /hello/foo /hello/bar /api/v1/users/foo /api/v1/users/bar /api/v2/users/foo /api/v2/users/bar
func (*Application) Run ¶
func (app *Application) Run(address string) error
Run starts a HTTP server with the given address.
func (*Application) RunTLS ¶
func (app *Application) RunTLS(address, certFile, keyFile string) error
RunTLS starts a HTTPS server with the given address, certfile and keyfile.
func (*Application) RunUnix ¶
func (app *Application) RunUnix(address string) error
RunUnix starts a HTTP Server which listening and serving HTTP requests through the specified unix socket with the given address.
func (*Application) Serve ¶ added in v0.4.0
func (app *Application) Serve(ln net.Listener) (err error)
Serve accepts incoming connections on the Listener ln.
func (*Application) ServeFiles ¶
func (app *Application) ServeFiles(path string, root http.FileSystem, opts ...RouteOption)
ServeFiles serves files from the given file system root.
Example ¶
app := Pure() app.ServeFiles("/static/", http.Dir("/path/to/static")) // sometimes, it is useful to treat http.FileServer as NotFoundHandler, // such as "/favicon.ico". app.NotFound = http.FileServer(http.Dir("public"))
Output:
func (*Application) ServeHTTP ¶
func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP makes the router implement the http.Handler interface.
func (*Application) Use ¶
func (app *Application) Use(middlewares ...MiddlewareFunc)
Use attaches global middlewares.
type Context ¶
type Context struct { Params Params Route *Route Request *http.Request Response http.ResponseWriter // contains filtered or unexported fields }
Context contains incoming request, route, params and manages outgoing response.
func (*Context) BasicAuth ¶
BasicAuth is a shortcut of http.Request.BasicAuth.
func (*Context) Blob ¶
Blob sends a response with the given status code, content type and blob data.
func (*Context) Context ¶
Context returns the context of request.
func (*Context) Cookie ¶
Cookie is a shortcut of http.Request.Cookie.
func (*Context) Cookies ¶
Cookies is a shortcut of http.Request.Cookies.
func (*Context) Decode ¶
Decode decodes request's input, stores it in the value pointed to by v.
func (*Context) DefaultQuery ¶
DefaultQuery returns the param for the given key, returns the default value if the param is not present.
func (*Context) Emit ¶
Emit sends a response with the given status code, content type and string body.
func (*Context) Error ¶
Error is a shortcut of http.Error.
func (*Context) FormValue ¶
FormValue is a shortcut of http.Request.FormValue.
func (*Context) GetHeader ¶
GetHeader is a shortcut of http.Request.Header.Get.
func (*Context) HTML ¶
HTML sends HTML response with status code, it also sets Content-Type as "text/html".
func (*Context) HTMLBlob ¶
HTMLBlob sends blob HTML response with status code, it also sets Content-Type as "text/html".
func (*Context) IsAJAX ¶
IsAJAX indicates whether it is an AJAX (XMLHttpRequest) request.
func (*Context) IsDelete ¶
IsDelete returns a boolean value indicates whether the request method is DELETE.
func (*Context) IsGet ¶
IsGet returns a boolean value indicates whether the request method is GET.
func (*Context) IsMethod ¶
IsMethod returns a boolean value indicates whether the request method is the given method.
func (*Context) IsOptions ¶
IsOptions returns a boolean value indicates whether the request method is OPTIONS.
func (*Context) IsPatch ¶
IsPatch returns a boolean value indicates whether the request method is PATCH.
func (*Context) IsPost ¶
IsPost returns a boolean value indicates whether the request method is POST.
func (*Context) IsPut ¶
IsPut returns a boolean value indicates whether the request method is PUT.
func (*Context) JSON ¶
JSON sends JSON response with status code, it also sets Content-Type as "application/json".
func (*Context) JSONBlob ¶
JSONBlob sends blob JSON response with status code, it also sets Content-Type as "application/json".
func (*Context) JSONP ¶
JSONP is a shortcut of JSONPCallback with specified callback param name.
func (*Context) JSONPBlob ¶
JSONPBlob is a shortcut of JSONPCallbackBlob with specified callback param name.
func (*Context) JSONPCallback ¶
JSONPCallback sends JSONP response with status code, it also sets Content-Type as "application/javascript". If the callback is not present, returns JSON response instead.
func (*Context) JSONPCallbackBlob ¶
JSONPCallbackBlob sends blob JSONP response with status code, it also sets Content-Type as "application/javascript". If the callback is not present, returns JSON response instead.
func (*Context) Logger ¶ added in v0.2.0
Logger returns the logger of application.
func (*Context) NotFound ¶
NotFound is a shortcut of http.NotFound.
func (*Context) PostFormValue ¶
PostFormValue is a shortcut of http.Request.PostFormValue.
func (*Context) QueryParam ¶
QueryParam returns the param for the given key.
func (*Context) QueryParams ¶
QueryParams returns request URL values.
func (*Context) QueryString ¶
QueryString returns the raw query of request URL.
func (*Context) Redirect ¶
Redirect is a shortcut of http.Redirect.
func (*Context) Render ¶
Render renders a template with data, and sends response with status code and content type. The content type defaults to HTML, which can be overridden by the fourth optional parameter.
func (*Context) RouteURL ¶
RouteURL returns the URL of the naming route.
func (*Context) SendFile ¶
SendFile sends a file to browser.
func (*Context) ServeContent ¶
ServeContent is a shortcut of http.ServeContent.
func (*Context) ServeFile ¶
ServeFile is a shortcut of http.ServeFile.
func (*Context) SetContentType ¶
SetContentType sets the content type header.
func (*Context) SetContentTypeHTML ¶
func (c *Context) SetContentTypeHTML()
SetContentTypeHTML sets the content type as HTML.
func (*Context) SetContentTypeJSON ¶
func (c *Context) SetContentTypeJSON()
SetContentTypeJSON sets the content type as JSON.
func (*Context) SetContentTypeText ¶
func (c *Context) SetContentTypeText()
SetContentTypeText sets the content type as text.
func (*Context) SetContentTypeXML ¶
func (c *Context) SetContentTypeXML()
SetContentTypeXML sets the content type as XML.
func (*Context) SetCookie ¶
SetCookie is a shortcut of http.SetCookie.
func (*Context) SetHeader ¶
SetHeader is a shortcut of http.ResponseWriter.Header().Set.
func (*Context) String ¶
String send string response with status code, it also sets Content-Type as "text/plain; charset=utf-8".
func (*Context) StringBlob ¶ added in v0.4.0
StringBlob sends blob HTML response with status code, it also sets Content-Type as "text/plain; charset=utf-8".
func (*Context) Stringf ¶
Stringf formats according to a format specifier and sends the resulting string with the status code, it also sets Content-Type as "text/plain; charset=utf-8".
func (*Context) Value ¶
func (c *Context) Value(key interface{}) interface{}
Value returns the value of the given key.
func (*Context) WithValue ¶
func (c *Context) WithValue(key, val interface{})
WithValue stores the given value under the given key.
func (*Context) Write ¶
Write is a shortcut of http.ResponseWriter.Write.
func (*Context) WriteHeader ¶
WriteHeader is a shortcut of http.ResponseWriter.WriteHeader.
func (*Context) WriteString ¶
WriteString writes the string data to response.
func (*Context) XML ¶
XML sends XML response with status code, it also sets Content-Type as "application/xml".
type Decoder ¶
type Decoder interface { // Decode decodes request's input and stores it in the value pointed to by v. Decode(req *http.Request, v interface{}) error }
Decoder is an interface that decodes request's input.
type Handle ¶
Handle is a function which handle incoming request and manage outgoing response.
func Chain ¶
func Chain(handle Handle, middlewares ...MiddlewareFunc) Handle
Chain wraps handle with middlewares, middlewares will be invoked in sequence.
Example ¶
m1 := echoMiddleware("m1") m2 := echoMiddleware("m2") handle := Chain(echoHandler("hello"), m1, m2) w := httptest.NewRecorder() handle(&Context{Response: w}) fmt.Println(w.Body.String())
Output: m1 m2 hello
func HandleHandler ¶
HandleHandler converts http.Handler to Handle.
func HandleHandlerFunc ¶
func HandleHandlerFunc(f http.HandlerFunc) Handle
HandleHandlerFunc converts http.HandlerFunc to Handle.
type LoggingOption ¶ added in v0.2.0
type LoggingOption func(*logging)
LoggingOption is a function that receives a logging instance.
func LoggingLogger ¶ added in v0.2.0
func LoggingLogger(logger log.Logger) LoggingOption
LoggingLogger is an option that sets logging logger.
type MiddlewareFunc ¶
MiddlewareFunc is a function that receives a handle and returns a handle.
func ErrorHandler ¶
func ErrorHandler() MiddlewareFunc
ErrorHandler returns a error handler middleware.
func Logging ¶ added in v0.2.0
func Logging(opts ...LoggingOption) MiddlewareFunc
Logging returns a logging middleware with the given options.
func Recovery ¶
func Recovery() MiddlewareFunc
Recovery returns a recovery middleware with debug enabled by default.
func ServerHeader ¶ added in v0.3.0
func ServerHeader(value string) MiddlewareFunc
ServerHeader is a middleware that sets Server header.
func WrapH ¶
func WrapH(h http.Handler) MiddlewareFunc
WrapH wraps a HTTP handler and returns a middleware.
type PanicError ¶ added in v0.2.0
type PanicError struct { // Context. Context *Context // Recovery data. Data interface{} // Debug stack. Stack []byte }
PanicError is an error that contains panic information.
func (PanicError) Error ¶ added in v0.2.0
func (e PanicError) Error() string
Error implements error interface.
type Param ¶
Param is a single URL parameter, consisting of a key and a value.
type Params ¶
type Params []Param
Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.
Example ¶
router := Pure() router.Get("/post/:year/:month/:title", func(c *Context) error { // converts param value to int. year, _ := c.Params.Int("year") month, _ := c.Params.Int("month") // ps.Int64("name") // converts to int64. // ps.Uint64("name") // converts to uint64. // ps.Float64("name") // converts to float64. // ps.Bool("name") // converts to boolean. fmt.Printf("%s posted on %04d-%02d\n", c.Params.String("title"), year, month) return nil }) req := httptest.NewRequest(http.MethodGet, "/post/2020/01/foo", nil) router.ServeHTTP(nil, req) req = httptest.NewRequest(http.MethodGet, "/post/2020/02/bar", nil) router.ServeHTTP(nil, req)
Output: foo posted on 2020-01 bar posted on 2020-02
func (Params) Bool ¶
Bool returns the boolean value of the given name.
func (Params) Float64 ¶
Float64 returns the float64 value of the given name.
func (Params) Int ¶
Int returns the int value of the given name.
func (Params) Int64 ¶
Int64 returns the int64 value of the given name.
func (Params) String ¶
String returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.
type Renderer ¶
Renderer is an interface for template engine.
type Route ¶
type Route struct {
// contains filtered or unexported fields
}
Route is a HTTP request handler.
Example ¶
app := Pure() app.Get("/posts/:page", func(c *Context) error { page, _ := c.Params.Int("page") route := c.Route prev, _ := route.URL("page", strconv.Itoa(page-1)) next, _ := route.URL("page", strconv.Itoa(page+1)) fmt.Printf("prev page url: %s\n", prev) fmt.Printf("next page url: %s\n", next) return nil }) req := httptest.NewRequest(http.MethodGet, "/posts/3", nil) app.ServeHTTP(nil, req)
Output: prev page url: /posts/2 next page url: /posts/4
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
RouteGroup implements an nested route group, see https://github.com/julienschmidt/httprouter/pull/89.
Example ¶
app := New() api := app.Group("/api", RouteGroupMiddleware(echoMiddleware("api"))) v1 := api.Group("/v1", RouteGroupMiddleware( echoMiddleware("v1"), echoMiddleware("authenticate"), )) v1.Get("/users/:name", func(c *Context) error { c.WriteString(fmt.Sprintf("user: %s", c.Params.String("name"))) return nil }, RouteMiddleware( echoMiddleware("fizz1"), echoMiddleware("fizz2"), )) v2 := api.Group("/v2", RouteGroupMiddleware( echoMiddleware("v2"), echoMiddleware("authenticate"), )) v2.Get("/users/:name", func(c *Context) error { c.WriteString(fmt.Sprintf("user: %s", c.Params.String("name"))) return nil }, RouteMiddleware( echoMiddleware("buzz1"), echoMiddleware("buzz2"), )) w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/api/v1/users/foo", nil) app.ServeHTTP(w, req) fmt.Println(w.Body.String()) w = httptest.NewRecorder() req = httptest.NewRequest(http.MethodGet, "/api/v2/users/bar", nil) app.ServeHTTP(w, req) fmt.Println(w.Body.String())
Output: api v1 authenticate fizz1 fizz2 user: foo api v2 authenticate buzz1 buzz2 user: bar
func (*RouteGroup) Any ¶
func (r *RouteGroup) Any(path string, handle Handle, opts ...RouteOption)
Any implements Router.Any.
func (*RouteGroup) Delete ¶
func (r *RouteGroup) Delete(path string, handle Handle, opts ...RouteOption)
Delete implements Router.Delete.
func (*RouteGroup) Get ¶
func (r *RouteGroup) Get(path string, handle Handle, opts ...RouteOption)
Get implements Router.Get.
func (*RouteGroup) Group ¶
func (r *RouteGroup) Group(path string, opts ...RouteGroupOption) Router
Group implements Router.Group.
func (*RouteGroup) Handle ¶
func (r *RouteGroup) Handle(method, path string, handle Handle, opts ...RouteOption)
Handle implements Router.Handle.
func (*RouteGroup) Handler ¶
func (r *RouteGroup) Handler(method, path string, handler http.Handler, opts ...RouteOption)
Handler implements Router.Handler.
func (*RouteGroup) HandlerFunc ¶
func (r *RouteGroup) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)
HandlerFunc implements Router.HandlerFunc.
func (*RouteGroup) Head ¶
func (r *RouteGroup) Head(path string, handle Handle, opts ...RouteOption)
Head implements Router.Head.
func (*RouteGroup) Options ¶
func (r *RouteGroup) Options(path string, handle Handle, opts ...RouteOption)
Options implements Router.Options.
func (*RouteGroup) Patch ¶
func (r *RouteGroup) Patch(path string, handle Handle, opts ...RouteOption)
Patch implements Router.Patch.
func (*RouteGroup) Post ¶
func (r *RouteGroup) Post(path string, handle Handle, opts ...RouteOption)
Post implements Router.Post.
func (*RouteGroup) Put ¶
func (r *RouteGroup) Put(path string, handle Handle, opts ...RouteOption)
Put implements Router.Put.
type RouteGroupOption ¶
type RouteGroupOption func(*RouteGroup)
RouteGroupOption applies options to a route group.
func RouteGroupMiddleware ¶
func RouteGroupMiddleware(middlewares ...MiddlewareFunc) RouteGroupOption
RouteGroupMiddleware is a option for chainging middlewares to a route group.
func RouteGroupName ¶
func RouteGroupName(name string) RouteGroupOption
RouteGroupName set the name of route group.
type RouteOption ¶
type RouteOption func(*Route)
RouteOption applies options to a route, see RouteName and RouteMiddleware.
func RouteMiddleware ¶
func RouteMiddleware(middlewares ...MiddlewareFunc) RouteOption
RouteMiddleware is a route option for chainging middlewares to a route.
func RouteName ¶
func RouteName(name string) RouteOption
RouteName is a route option for naming a route.
type Router ¶
type Router interface { // Group creates a sub Router with the given optional route group options. Group(path string, opts ...RouteGroupOption) Router // Get registers a new GET request handler function with the given path and optional route options. Get(path string, handle Handle, opts ...RouteOption) // Head registers a new HEAD request handler function with the given path and optional route options. Head(path string, handle Handle, opts ...RouteOption) // Options registers a new Options request handler function with the given path and optional route options. Options(path string, handle Handle, opts ...RouteOption) // Post registers a new POST request handler function with the given path and optional route options. Post(path string, handle Handle, opts ...RouteOption) // Put registers a new PUT request handler function with the given path and optional route options. Put(path string, handle Handle, opts ...RouteOption) // Patch registers a new PATCH request handler function with the given path and optional route options. Patch(path string, handle Handle, opts ...RouteOption) // Delete registers a new DELETE request handler function with the given path and optional route options. Delete(path string, handle Handle, opts ...RouteOption) // Any registers a new request handler function that matches any HTTP methods with the given path and // optional route options. GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH. Any(path string, handle Handle, opts ...RouteOption) // HandleFunc registers a new request handler function with the given path, method and optional route options. // // For Get, Head, Options, Post, Put, Patch and Delete requests the respective shortcut // functions can be used. // // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). Handle(method, path string, handle Handle, opts ...RouteOption) // Handler is an adapter for registering http.Handler. Handler(method, path string, handler http.Handler, opts ...RouteOption) // HandlerFunc is an adapter for registering http.HandlerFunc. HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption) }
Router is an router interface.
type Skipper ¶
Skipper is a function that indicates whether current request is skippable.
func PathSkipper ¶
PathSkipper returns a skipper with the given patterns. Pattern has two forms, one is that contains a certain path, another contains a wildcard, both of them are case-insensitive.
Pattern Path Skippable "" "/" false "/" "/" true "/" "/login" false "/login" "/login" true "/login" "/Login" true "/login" "/LOGIN" true "/guest*" "/guest" true "/guest*" "/guest/foo" true "/guest*" "/guest/bar" true
type StatusError ¶
StatusError implements Error interface.
func NewError ¶
func NewError(code int, err error) StatusError
NewError returns a status error with the given code and error.