clevergo

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2021 License: MIT Imports: 23 Imported by: 38

README

CleverGo

Build Status Coverage Status Go Report Card Go.Dev reference Release Downloads Chat Community

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

go get -u clevergo.tech/clevergo

Benchmark

Features

  • Full features of HTTP router.
  • 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.
  • Logger: a generic logger interface, supports zap and logrus. Logger can be used in middleware or handler.
  • ...

Examples

Checkout example for details.

Contribute

Contributions are welcome.

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

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

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

errors

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

func (app *Application) RouteURL(name string, args ...string) (*url.URL, error)

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

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

BasicAuth is a shortcut of http.Request.BasicAuth.

func (*Context) Blob

func (c *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) Context

func (c *Context) Context() context.Context

Context returns the context of request.

func (*Context) Cookie

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

Cookie is a shortcut of http.Request.Cookie.

func (*Context) Cookies

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

Cookies is a shortcut of http.Request.Cookies.

func (*Context) Decode

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

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

func (*Context) DefaultQuery

func (c *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

func (c *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 (c *Context) Error(code int, msg string) error

Error is a shortcut of http.Error.

func (*Context) FormValue

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

FormValue is a shortcut of http.Request.FormValue.

func (*Context) GetHeader

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

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

func (*Context) HTML

func (c *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

func (c *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) Host

func (c *Context) Host() string

Host returns http.Request.Host.

func (*Context) IsAJAX

func (c *Context) IsAJAX() bool

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

func (*Context) IsDelete

func (c *Context) IsDelete() bool

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

func (*Context) IsGet

func (c *Context) IsGet() bool

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

func (*Context) IsMethod

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

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

func (*Context) IsOptions

func (c *Context) IsOptions() bool

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

func (*Context) IsPatch

func (c *Context) IsPatch() bool

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

func (*Context) IsPost

func (c *Context) IsPost() bool

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

func (*Context) IsPut

func (c *Context) IsPut() bool

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

func (*Context) JSON

func (c *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

func (c *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

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

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

func (*Context) JSONPBlob

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

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

func (*Context) JSONPCallback

func (c *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

func (c *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) Logger added in v0.2.0

func (c *Context) Logger() log.Logger

Logger returns the logger of application.

func (*Context) NotFound

func (c *Context) NotFound() error

NotFound is a shortcut of http.NotFound.

func (*Context) PostFormValue

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

PostFormValue is a shortcut of http.Request.PostFormValue.

func (*Context) QueryParam

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

QueryParam returns the param for the given key.

func (*Context) QueryParams

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

QueryParams returns request URL values.

func (*Context) QueryString

func (c *Context) QueryString() string

QueryString returns the raw query of request URL.

func (*Context) Redirect

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

Redirect is a shortcut of http.Redirect.

func (*Context) Render

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

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

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

RouteURL returns the URL of the naming route.

func (*Context) SendFile

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

SendFile sends a file to browser.

func (*Context) ServeContent

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

ServeContent is a shortcut of http.ServeContent.

func (*Context) ServeFile

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

ServeFile is a shortcut of http.ServeFile.

func (*Context) SetContentType

func (c *Context) SetContentType(v string)

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

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

SetCookie is a shortcut of http.SetCookie.

func (*Context) SetHeader

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

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

func (*Context) String

func (c *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) StringBlob added in v0.4.0

func (c *Context) StringBlob(code int, bs []byte) error

StringBlob sends blob HTML response with status code, it also sets Content-Type as "text/plain; charset=utf-8".

func (*Context) Stringf

func (c *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 (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

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

Write is a shortcut of http.ResponseWriter.Write.

func (*Context) WriteHeader

func (c *Context) WriteHeader(code int)

WriteHeader is a shortcut of http.ResponseWriter.WriteHeader.

func (*Context) WriteString

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

WriteString writes the string data to response.

func (*Context) XML

func (c *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

func (c *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

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

type Error interface {
	error
	Status() int
}

Error defines an HTTP response error.

type Handle

type Handle func(c *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 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 Map

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

func WrapHH

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

WrapHH wraps func(http.Handler) 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

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

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

type Renderer interface {
	Render(w io.Writer, name string, data interface{}, c *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
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

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

type Skipper func(c *Context) bool

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

func PathSkipper

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

type StatusError struct {
	Code int
	Err  error
}

StatusError implements Error interface.

func NewError

func NewError(code int, err error) StatusError

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

func (StatusError) Error

func (e StatusError) Error() string

Error implements error.Error.

func (StatusError) Status

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