clevergo

package module
v1.12.2 Latest Latest
Warning

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

Go to latest
Published: May 12, 2020 License: BSD-3-Clause Imports: 18 Imported by: 17

README

CleverGo

Build Status Go Report Card GoDoc Release Sourcegraph English 简体中文 繁體中文

CleverGo is a lightweight, feature rich and trie based high performance HTTP request router.

Benchmark

Features

  • High Performance: extremely fast, see Benchmark.
  • Gradual learning curve: you can learn the entire usages by going through the documentation in half an hour.
  • Reverse Route Generation: allow generating URLs by named route or matched route.
  • Route Group: as known as subrouter.
  • Friendly to APIs: it is easy to design RESTful APIs and versioning your APIs by route group.
  • Middleware: plug middleware in route group or particular route, supports global middleware as well. Compatible with most of third-party middleware.
  • Error Handler: record error and format error response.

Contribute

Contributions are welcome.

  • Give it a ⭐ and spread the package.
  • File an issue to ask questions, request features or report bugs.
  • Fork and make a pull request.
  • Improve documentations.
Contributors

This project exists thanks to all the people who contribute.

Credit

See CREDIT.md.

Documentation

Overview

Package clevergo is a trie based high performance HTTP request router.

Index

Examples

Constants

This section is empty.

Variables

Errors

View Source
var (
	ErrRendererNotRegister = errors.New("renderer not registered")
	ErrDecoderNotRegister  = errors.New("decoder not registered")
)

errors

Functions

func CleanPath

func CleanPath(p string) string

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:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. 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 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 added in v1.10.0

func (ctx *Context) BasicAuth() (username, password string, ok bool)

BasicAuth is a shortcut of http.Request.BasicAuth.

func (*Context) Blob added in v1.9.0

func (ctx *Context) Blob(code int, contentType string, bs []byte) (err error)

Blob sends a response with the given status code, content type and blob data.

func (*Context) Cookie added in v1.9.0

func (ctx *Context) Cookie(name string) (*http.Cookie, error)

Cookie is a shortcut of http.Request.Cookie.

func (*Context) Cookies added in v1.9.0

func (ctx *Context) Cookies() []*http.Cookie

Cookies is a shortcut of http.Request.Cookies.

func (*Context) Decode added in v1.11.0

func (ctx *Context) Decode(v interface{}) (err error)

Decode decodes request's input, stores it in the value pointed to by v.

func (*Context) DefaultQuery added in v1.10.0

func (ctx *Context) DefaultQuery(key, defaultVlue string) string

DefaultQuery returns the param for the given key, returns the default value if the param is not present.

func (*Context) Emit added in v1.9.0

func (ctx *Context) Emit(code int, contentType string, body string) (err error)

Emit sends a response with the given status code, content type and string body.

func (*Context) Error

func (ctx *Context) Error(code int, msg string) error

Error is a shortcut of http.Error.

func (*Context) FormValue added in v1.9.0

func (ctx *Context) FormValue(key string) string

FormValue is a shortcut of http.Request.FormValue.

func (*Context) GetHeader added in v1.8.0

func (ctx *Context) GetHeader(name string) string

GetHeader is a shortcut of http.Request.Header.Get.

func (*Context) HTML added in v1.9.0

func (ctx *Context) HTML(code int, html string) error

HTML sends HTML response with status code, it also sets Content-Type as "text/html".

func (*Context) HTMLBlob added in v1.9.0

func (ctx *Context) HTMLBlob(code int, bs []byte) error

HTMLBlob sends blob HTML response with status code, it also sets Content-Type as "text/html".

func (*Context) IsAJAX added in v1.7.0

func (ctx *Context) IsAJAX() bool

IsAJAX indicates whether it is an AJAX (XMLHttpRequest) request.

func (*Context) IsDelete added in v1.4.0

func (ctx *Context) IsDelete() bool

IsDelete returns a boolean value indicates whether the request method is DELETE.

func (*Context) IsGet added in v1.4.0

func (ctx *Context) IsGet() bool

IsGet returns a boolean value indicates whether the request method is GET.

func (*Context) IsMethod added in v1.4.0

func (ctx *Context) IsMethod(method string) bool

IsMethod returns a boolean value indicates whether the request method is the given method.

func (*Context) IsOptions added in v1.4.0

func (ctx *Context) IsOptions() bool

IsOptions returns a boolean value indicates whether the request method is OPTIONS.

func (*Context) IsPatch added in v1.4.0

func (ctx *Context) IsPatch() bool

IsPatch returns a boolean value indicates whether the request method is PATCH.

func (*Context) IsPost added in v1.4.0

func (ctx *Context) IsPost() bool

IsPost returns a boolean value indicates whether the request method is POST.

func (*Context) IsPut added in v1.4.0

func (ctx *Context) IsPut() bool

IsPut returns a boolean value indicates whether the request method is PUT.

func (*Context) JSON added in v1.9.0

func (ctx *Context) JSON(code int, data interface{}) error

JSON sends JSON response with status code, it also sets Content-Type as "application/json".

func (*Context) JSONBlob added in v1.9.0

func (ctx *Context) JSONBlob(code int, bs []byte) error

JSONBlob sends blob JSON response with status code, it also sets Content-Type as "application/json".

func (*Context) JSONP added in v1.9.0

func (ctx *Context) JSONP(code int, data interface{}) error

JSONP is a shortcut of JSONPCallback with specified callback param name.

func (*Context) JSONPBlob added in v1.9.0

func (ctx *Context) JSONPBlob(code int, bs []byte) error

JSONPBlob is a shortcut of JSONPCallbackBlob with specified callback param name.

func (*Context) JSONPCallback added in v1.9.0

func (ctx *Context) JSONPCallback(code int, callback string, data interface{}) error

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

func (ctx *Context) JSONPCallbackBlob(code int, callback string, bs []byte) (err error)

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

func (ctx *Context) NotFound() error

NotFound is a shortcut of http.NotFound.

func (*Context) PostFormValue added in v1.9.0

func (ctx *Context) PostFormValue(key string) string

PostFormValue is a shortcut of http.Request.PostFormValue.

func (*Context) QueryParam added in v1.9.0

func (ctx *Context) QueryParam(key string) string

QueryParam returns the param for the given key.

func (*Context) QueryParams added in v1.9.0

func (ctx *Context) QueryParams() url.Values

QueryParams returns request URL values.

func (*Context) QueryString added in v1.9.0

func (ctx *Context) QueryString() string

QueryString returns the raw query of request URL.

func (*Context) Redirect

func (ctx *Context) Redirect(code int, url string) error

Redirect is a shortcut of http.Redirect.

func (*Context) Render added in v1.9.0

func (ctx *Context) Render(code int, name string, data interface{}) (err error)

Render renders a template with data, and sends HTML response with status code.

func (*Context) RouteURL added in v1.9.0

func (ctx *Context) RouteURL(name string, args ...string) (*url.URL, error)

RouteURL returns the URL of the naming route.

func (*Context) SendFile added in v1.10.0

func (ctx *Context) SendFile(filename string, r io.Reader) (err error)

SendFile sends a file to browser.

func (*Context) ServeContent added in v1.10.0

func (ctx *Context) ServeContent(name string, modtime time.Time, content io.ReadSeeker) error

ServeContent is a shortcut of http.ServeContent.

func (*Context) ServeFile added in v1.10.0

func (ctx *Context) ServeFile(name string) error

ServeFile is a shortcut of http.ServeFile.

func (*Context) SetContentType

func (ctx *Context) SetContentType(v string)

SetContentType sets the content type header.

func (*Context) SetContentTypeHTML

func (ctx *Context) SetContentTypeHTML()

SetContentTypeHTML sets the content type as HTML.

func (*Context) SetContentTypeJSON

func (ctx *Context) SetContentTypeJSON()

SetContentTypeJSON sets the content type as JSON.

func (*Context) SetContentTypeText

func (ctx *Context) SetContentTypeText()

SetContentTypeText sets the content type as text.

func (*Context) SetContentTypeXML

func (ctx *Context) SetContentTypeXML()

SetContentTypeXML sets the content type as XML.

func (*Context) SetCookie added in v1.5.0

func (ctx *Context) SetCookie(cookie *http.Cookie)

SetCookie is a shortcut of http.SetCookie.

func (*Context) SetHeader added in v1.12.0

func (ctx *Context) SetHeader(key, value string)

SetHeader is a shortcut of http.ResponseWriter.Header().Set.

func (*Context) String added in v1.9.0

func (ctx *Context) String(code int, s string) error

String send string response with status code, it also sets Content-Type as "text/plain; charset=utf-8".

func (*Context) Stringf added in v1.11.0

func (ctx *Context) Stringf(code int, format string, a ...interface{}) error

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 (ctx *Context) Value(key interface{}) interface{}

Value returns the value of the given key.

func (*Context) WithValue

func (ctx *Context) WithValue(key, val interface{})

WithValue stores the given value under the given key.

func (*Context) Write

func (ctx *Context) Write(data []byte) (int, error)

Write is a shortcut of http.ResponseWriter.Write.

func (*Context) WriteHeader added in v1.7.0

func (ctx *Context) WriteHeader(code int)

WriteHeader is a shortcut of http.ResponseWriter.WriteHeader.

func (*Context) WriteString

func (ctx *Context) WriteString(data string) (int, error)

WriteString writes the string data to response.

func (*Context) XML added in v1.9.0

func (ctx *Context) XML(code int, data interface{}) error

XML sends XML response with status code, it also sets Content-Type as "application/xml".

func (*Context) XMLBlob added in v1.9.0

func (ctx *Context) XMLBlob(code int, bs []byte) error

XMLBlob sends blob XML response with status code, it also sets Content-Type as "application/xml".

type Decoder added in v1.11.0

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 Error added in v0.2.0

type Error interface {
	error
	Status() int
}

Error defines an HTTP response error.

type ErrorHandler added in v0.2.0

type ErrorHandler interface {
	Handle(ctx *Context, err error)
}

ErrorHandler is a handler to handle error returns from handle.

type Handle

type Handle func(ctx *Context) error

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

func HandleHandler(handler http.Handler) Handle

HandleHandler converts http.Handler to Handle.

func HandleHandlerFunc

func HandleHandlerFunc(f http.HandlerFunc) Handle

HandleHandlerFunc converts http.HandlerFunc to Handle.

type IRouter

type IRouter interface {
	// Group creates a sub IRouter with the given optional route group options.
	Group(path string, opts ...RouteGroupOption) IRouter

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

IRouter is an router interface.

type Map added in v1.11.0

type Map map[string]interface{}

Map is an alias of map[string]interface{}.

type MiddlewareFunc

type MiddlewareFunc func(Handle) Handle

MiddlewareFunc is a function that receives a handle and returns a handle.

func Recovery added in v1.6.0

func Recovery(debug bool) MiddlewareFunc

Recovery returns a recovery middleware.

func RecoveryLogger added in v1.9.0

func RecoveryLogger(debug bool, logger *log.Logger) MiddlewareFunc

RecoveryLogger returns a recovery middleware with the given logger.

func WrapH added in v1.8.0

func WrapH(h http.Handler) MiddlewareFunc

WrapH wraps a HTTP handler and returns a middleware.

func WrapHH added in v1.8.0

func WrapHH(fn func(http.Handler) http.Handler) MiddlewareFunc

WrapHH wraps func(http.Handler) http.Handler and returns a middleware.

type Param

type Param struct {
	Key   string
	Value string
}

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 := NewRouter()
router.Get("/post/:year/:month/:title", func(ctx *Context) error {
	// converts param value to int.
	year, _ := ctx.Params.Int("year")
	month, _ := ctx.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", ctx.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

func (ps Params) Bool(name string) (bool, error)

Bool returns the boolean value of the given name.

func (Params) Float64

func (ps Params) Float64(name string) (float64, error)

Float64 returns the float64 value of the given name.

func (Params) Int

func (ps Params) Int(name string) (int, error)

Int returns the int value of the given name.

func (Params) Int64

func (ps Params) Int64(name string) (int64, error)

Int64 returns the int64 value of the given name.

func (Params) String

func (ps Params) String(name string) 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.

func (Params) Uint64

func (ps Params) Uint64(name string) (uint64, error)

Uint64 returns the uint64 value of the given name.

type Renderer added in v1.9.0

type Renderer interface {
	Render(w io.Writer, name string, data interface{}, ctx *Context) error
}

Renderer is an interface for template engine.

type Route

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

Route is a HTTP request handler.

Example
router := NewRouter()
router.Get("/posts/:page", func(ctx *Context) error {
	page, _ := ctx.Params.Int("page")
	route := ctx.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)
router.ServeHTTP(nil, req)
Output:

prev page url: /posts/2
next page url: /posts/4

func (*Route) URL

func (r *Route) URL(args ...string) (*url.URL, error)

URL creates an url with the given arguments.

It accepts a sequence of key/value pairs for the route variables, otherwise errWrongArgumentsNumber will be returned.

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
router := NewRouter()
api := router.Group("/api", RouteGroupMiddleware(echoMiddleware("api")))

v1 := api.Group("/v1", RouteGroupMiddleware(
	echoMiddleware("v1"),
	echoMiddleware("authenticate"),
))
v1.Get("/users/:name", func(ctx *Context) error {
	ctx.WriteString(fmt.Sprintf("user: %s", ctx.Params.String("name")))
	return nil
}, RouteMiddleware(
	echoMiddleware("fizz1"),
	echoMiddleware("fizz2"),
))

v2 := api.Group("/v2", RouteGroupMiddleware(
	echoMiddleware("v2"),
	echoMiddleware("authenticate"),
))
v2.Get("/users/:name", func(ctx *Context) error {
	ctx.WriteString(fmt.Sprintf("user: %s", ctx.Params.String("name")))
	return nil
}, RouteMiddleware(
	echoMiddleware("buzz1"),
	echoMiddleware("buzz2"),
))

w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/users/foo", nil)
router.ServeHTTP(w, req)
fmt.Println(w.Body.String())

w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/v2/users/bar", nil)
router.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 added in v1.12.0

func (r *RouteGroup) Any(path string, handle Handle, opts ...RouteOption)

Any implements IRouter.Any.

func (*RouteGroup) Delete

func (r *RouteGroup) Delete(path string, handle Handle, opts ...RouteOption)

Delete implements IRouter.Delete.

func (*RouteGroup) Get

func (r *RouteGroup) Get(path string, handle Handle, opts ...RouteOption)

Get implements IRouter.Get.

func (*RouteGroup) Group

func (r *RouteGroup) Group(path string, opts ...RouteGroupOption) IRouter

Group implements IRouter.Group.

func (*RouteGroup) Handle

func (r *RouteGroup) Handle(method, path string, handle Handle, opts ...RouteOption)

Handle implements IRouter.Handle.

func (*RouteGroup) Handler

func (r *RouteGroup) Handler(method, path string, handler http.Handler, opts ...RouteOption)

Handler implements IRouter.Handler.

func (*RouteGroup) HandlerFunc

func (r *RouteGroup) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)

HandlerFunc implements IRouter.HandlerFunc.

func (*RouteGroup) Head

func (r *RouteGroup) Head(path string, handle Handle, opts ...RouteOption)

Head implements IRouter.Head.

func (*RouteGroup) Options

func (r *RouteGroup) Options(path string, handle Handle, opts ...RouteOption)

Options implements IRouter.Options.

func (*RouteGroup) Patch

func (r *RouteGroup) Patch(path string, handle Handle, opts ...RouteOption)

Patch implements IRouter.Patch.

func (*RouteGroup) Post

func (r *RouteGroup) Post(path string, handle Handle, opts ...RouteOption)

Post implements IRouter.Post.

func (*RouteGroup) Put

func (r *RouteGroup) Put(path string, handle Handle, opts ...RouteOption)

Put implements IRouter.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 added in v1.5.0

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

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

	// Error Handler.
	ErrorHandler ErrorHandler

	// If enabled, use the request.URL.RawPath instead of request.URL.Path.
	UseRawPath bool

	Renderer Renderer

	Decoder Decoder
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func NewRouter

func NewRouter() *Router

NewRouter returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) Any added in v1.12.0

func (r *Router) Any(path string, handle Handle, opts ...RouteOption)

Any implements IRouter.Any.

func (*Router) Delete

func (r *Router) Delete(path string, handle Handle, opts ...RouteOption)

Delete implements IRouter.Delete.

func (*Router) Get

func (r *Router) Get(path string, handle Handle, opts ...RouteOption)

Get implements IRouter.Get.

func (*Router) Group

func (r *Router) Group(path string, opts ...RouteGroupOption) IRouter

Group implements IRouter.Group.

func (*Router) Handle

func (r *Router) Handle(method, path string, handle Handle, opts ...RouteOption)

Handle implements IRouter.Handle.

func (*Router) HandleError added in v0.2.0

func (r *Router) HandleError(ctx *Context, err error)

HandleError handles error.

func (*Router) Handler

func (r *Router) Handler(method, path string, handler http.Handler, opts ...RouteOption)

Handler implements IRouter.Handler.

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)

HandlerFunc implements IRouter.HandlerFunc.

func (*Router) Head

func (r *Router) Head(path string, handle Handle, opts ...RouteOption)

Head implements IRouter.Head.

func (*Router) Lookup

func (r *Router) 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 (*Router) Options

func (r *Router) Options(path string, handle Handle, opts ...RouteOption)

Options implements IRouter.Options.

func (*Router) Patch

func (r *Router) Patch(path string, handle Handle, opts ...RouteOption)

Patch implements IRouter.Patch.

func (*Router) Post

func (r *Router) Post(path string, handle Handle, opts ...RouteOption)

Post implements IRouter.Post.

func (*Router) Put

func (r *Router) Put(path string, handle Handle, opts ...RouteOption)

Put implements IRouter.Put.

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, root http.FileSystem, opts ...RouteOption)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:

router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
Example
router := NewRouter()

router.ServeFiles("/static/*filepath", http.Dir("/path/to/static"))

// sometimes, it is useful to treat http.FileServer as NotFoundHandler,
// such as "/favicon.ico".
router.NotFound = http.FileServer(http.Dir("public"))
Output:

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

func (*Router) URL

func (r *Router) URL(name string, args ...string) (*url.URL, error)

URL creates an url with the given route name and arguments.

Example
router := NewRouter()
router.Get("/hello/:name", func(ctx *Context) error {
	return nil
}, RouteName("hello"))
// nested routes group
api := router.Group("/api")

v1 := api.Group("/v1")
// the group path will become the prefix of route name.
v1.Get("/users/:name", func(ctx *Context) error {
	return nil
}, RouteName("user"))

// specified the name of the route group.
v2 := api.Group("/v2", RouteGroupName("/apiV2"))
v2.Get("/users/:name", func(ctx *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, _ := router.URL(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 (*Router) Use added in v1.5.0

func (r *Router) Use(middlewares ...MiddlewareFunc)

Use attaches global middlewares.

type Skipper added in v1.12.0

type Skipper func(ctx *Context) bool

Skipper is a function that indicates whether current request is skippable.

func PathSkipper added in v1.12.0

func PathSkipper(patterns ...string) Skipper

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 added in v0.2.0

type StatusError struct {
	Code int
	Err  error
}

StatusError implements Error interface.

func NewError added in v1.4.1

func NewError(code int, err error) StatusError

NewError returns a status error with the given code and error.

func (StatusError) Error added in v0.2.0

func (e StatusError) Error() string

Error implements error.Error.

func (StatusError) Status added in v0.2.0

func (e StatusError) Status() int

Status implements Error.Status.

Jump to

Keyboard shortcuts

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