Search and commands

↑ ↓ to select · Enter to open · Esc to close

Type to search packages.

clevergo

v0.6.0
clevergo.tech/clevergo

Documentation

pkg.go.dev ↗

Table of contents

↓ to select · Enter to jump· Shift+Enter for source

151 matches

Top ↑

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

Variables

ErrRendererNotRegister (2 declarations)

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

errors

ErrNotFound (2 declarations)

var (
	ErrNotFound         = StatusError{http.StatusNotFound, errors.New(http.StatusText(http.StatusNotFound))}
	ErrMethodNotAllowed = StatusError{http.StatusMethodNotAllowed, errors.New(http.StatusText(http.StatusMethodNotAllowed))}
)

Errors

Functions

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

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

New

func New() *Application

New returns an application which enable recovery, error handler, server header and logging middleware by default.

Pure

func Pure() *Application

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

Application.Any

func (app *Application) Any(path string, handle Handle, opts ...RouteOption)

Any implements Router.Any.

Application.Delete

func (app *Application) Delete(path string, handle Handle, opts ...RouteOption)

Delete implements Router.Delete.

Application.Get

func (app *Application) Get(path string, handle Handle, opts ...RouteOption)

Get implements Router.Get.

Application.Group

func (app *Application) Group(path string, opts ...RouteGroupOption) Router

Group implements Router.Group.

Application.Handle

func (app *Application) Handle(method, path string, handle Handle, opts ...RouteOption)

Handle implements Router.Handle.

Application.Handler

func (app *Application) Handler(method, path string, handler http.Handler, opts ...RouteOption)

Handler implements Router.Handler.

Application.HandlerFunc

func (app *Application) HandlerFunc(method, path string, f http.HandlerFunc, opts ...RouteOption)

HandlerFunc implements Router.HandlerFunc.

Application.Head

func (app *Application) Head(path string, handle Handle, opts ...RouteOption)

Head implements Router.Head.

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.

Application.Options

func (app *Application) Options(path string, handle Handle, opts ...RouteOption)

Options implements Router.Options.

Application.Patch

func (app *Application) Patch(path string, handle Handle, opts ...RouteOption)

Patch implements Router.Patch.

Application.Post

func (app *Application) Post(path string, handle Handle, opts ...RouteOption)

Post implements Router.Post.

Application.Put

func (app *Application) Put(path string, handle Handle, opts ...RouteOption)

Put implements Router.Put.

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

	api := app.Group("/api")

	v1 := api.Group("/v1")

	v1.Get("/users/:name", func(c *Context) error {
		return nil
	}, RouteName("user"))

	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

Application.Run

func (app *Application) Run(address string) error

Run starts a HTTP server with the given address.

Application.RunTLS

func (app *Application) RunTLS(address, certFile, keyFile string) error

RunTLS starts a HTTPS server with the given address, certfile and keyfile.

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.

Application.Serve

func (app *Application) Serve(ln net.Listener) (err error)

Serve accepts incoming connections on the Listener ln.

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

	app.NotFound = http.FileServer(http.Dir("public"))
}

Application.ServeHTTP

func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

Application.Use

func (app *Application) Use(middlewares ...MiddlewareFunc)

Use attaches global middlewares.

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.

Context.BasicAuth

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

BasicAuth is a shortcut of http.Request.BasicAuth.

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.

Context.Context

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

Context returns the context of request.

Context.Cookie

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

Cookie is a shortcut of http.Request.Cookie.

Context.Cookies

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

Cookies is a shortcut of http.Request.Cookies.

Context.Decode

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

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

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.

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.

Context.Error

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

Error is a shortcut of http.Error.

Context.FormValue

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

FormValue is a shortcut of http.Request.FormValue.

Context.GetHeader

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

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

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

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

Context.Host

func (c *Context) Host() string

Host returns http.Request.Host.

Context.IsAJAX

func (c *Context) IsAJAX() bool

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

Context.IsDelete

func (c *Context) IsDelete() bool

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

Context.IsGet

func (c *Context) IsGet() bool

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

Context.IsMethod

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

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

Context.IsOptions

func (c *Context) IsOptions() bool

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

Context.IsPatch

func (c *Context) IsPatch() bool

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

Context.IsPost

func (c *Context) IsPost() bool

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

Context.IsPut

func (c *Context) IsPut() bool

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

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

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

Context.JSONP

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

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

Context.JSONPBlob

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

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

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.

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.

Context.Logger

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

Logger returns the logger of application.

Context.NotFound

func (c *Context) NotFound() error

NotFound is a shortcut of http.NotFound.

Context.PostFormValue

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

PostFormValue is a shortcut of http.Request.PostFormValue.

Context.QueryParam

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

QueryParam returns the param for the given key.

Context.QueryParams

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

QueryParams returns request URL values.

Context.QueryString

func (c *Context) QueryString() string

QueryString returns the raw query of request URL.

Context.Redirect

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

Redirect is a shortcut of http.Redirect.

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.

Context.RouteURL

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

RouteURL returns the URL of the naming route.

Context.SendFile

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

SendFile sends a file to browser.

Context.ServeContent

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

ServeContent is a shortcut of http.ServeContent.

Context.ServeFile

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

ServeFile is a shortcut of http.ServeFile.

Context.SetContentType

func (c *Context) SetContentType(v string)

SetContentType sets the content type header.

Context.SetContentTypeHTML

func (c *Context) SetContentTypeHTML()

SetContentTypeHTML sets the content type as HTML.

Context.SetContentTypeJSON

func (c *Context) SetContentTypeJSON()

SetContentTypeJSON sets the content type as JSON.

Context.SetContentTypeText

func (c *Context) SetContentTypeText()

SetContentTypeText sets the content type as text.

Context.SetContentTypeXML

func (c *Context) SetContentTypeXML()

SetContentTypeXML sets the content type as XML.

Context.SetCookie

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

SetCookie is a shortcut of http.SetCookie.

Context.SetHeader

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

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

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

Context.StringBlob

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

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

Context.Value

func (c *Context) Value(key interface{}) interface{}

Value returns the value of the given key.

Context.WithValue

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

WithValue stores the given value under the given key.

Context.Write

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

Write is a shortcut of http.ResponseWriter.Write.

Context.WriteHeader

func (c *Context) WriteHeader(code int)

WriteHeader is a shortcut of http.ResponseWriter.WriteHeader.

Context.WriteString

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

WriteString writes the string data to response.

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

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

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.

Error

type Error interface {
	error
	Status() int
}

Error defines an HTTP response error.

Handle

type Handle func(c *Context) error

Handle is a function which handle incoming request and manage outgoing response.

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

HandleHandler

func HandleHandler(handler http.Handler) Handle

HandleHandler converts http.Handler to Handle.

HandleHandlerFunc

func HandleHandlerFunc(f http.HandlerFunc) Handle

HandleHandlerFunc converts http.HandlerFunc to Handle.

LoggingOption

type LoggingOption func(*logging)

LoggingOption is a function that receives a logging instance.

LoggingLogger

func LoggingLogger(logger log.Logger) LoggingOption

LoggingLogger is an option that sets logging logger.

Map

type Map map[string]interface{}

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

MiddlewareFunc

type MiddlewareFunc func(Handle) Handle

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

ErrorHandler

func ErrorHandler() MiddlewareFunc

ErrorHandler returns a error handler middleware.

Logging

func Logging(opts ...LoggingOption) MiddlewareFunc

Logging returns a logging middleware with the given options.

Recovery

func Recovery() MiddlewareFunc

Recovery returns a recovery middleware with debug enabled by default.

ServerHeader

func ServerHeader(value string) MiddlewareFunc

ServerHeader is a middleware that sets Server header.

WrapH

func WrapH(h http.Handler) MiddlewareFunc

WrapH wraps a HTTP handler and returns a middleware.

WrapHH

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

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

PanicError

type PanicError struct {
	// Context.
	Context *Context

	// Recovery data.
	Data interface{}

	// Debug stack.
	Stack []byte
}

PanicError is an error that contains panic information.

PanicError.Error

func (e PanicError) Error() string

Error implements error interface.

Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

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 {

		year, _ := c.Params.Int("year")
		month, _ := c.Params.Int("month")

		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

Params.Bool

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

Bool returns the boolean value of the given name.

Params.Float64

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

Float64 returns the float64 value of the given name.

Params.Int

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

Int returns the int value of the given name.

Params.Int64

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

Int64 returns the int64 value of the given name.

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.

Params.Uint64

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

Uint64 returns the uint64 value of the given name.

Renderer

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

Renderer is an interface for template engine.

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

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.

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

RouteGroup.Any

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

Any implements Router.Any.

RouteGroup.Delete

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

Delete implements Router.Delete.

RouteGroup.Get

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

Get implements Router.Get.

RouteGroup.Group

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

Group implements Router.Group.

RouteGroup.Handle

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

Handle implements Router.Handle.

RouteGroup.Handler

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

Handler implements Router.Handler.

RouteGroup.HandlerFunc

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

HandlerFunc implements Router.HandlerFunc.

RouteGroup.Head

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

Head implements Router.Head.

RouteGroup.Options

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

Options implements Router.Options.

RouteGroup.Patch

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

Patch implements Router.Patch.

RouteGroup.Post

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

Post implements Router.Post.

RouteGroup.Put

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

Put implements Router.Put.

RouteGroupOption

type RouteGroupOption func(*RouteGroup)

RouteGroupOption applies options to a route group.

RouteGroupMiddleware

func RouteGroupMiddleware(middlewares ...MiddlewareFunc) RouteGroupOption

RouteGroupMiddleware is a option for chainging middlewares to a route group.

RouteGroupName

func RouteGroupName(name string) RouteGroupOption

RouteGroupName set the name of route group.

RouteOption

type RouteOption func(*Route)

RouteOption applies options to a route, see RouteName and RouteMiddleware.

RouteMiddleware

func RouteMiddleware(middlewares ...MiddlewareFunc) RouteOption

RouteMiddleware is a route option for chainging middlewares to a route.

RouteName

func RouteName(name string) RouteOption

RouteName is a route option for naming a route.

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.

Skipper

type Skipper func(c *Context) bool

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

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

StatusError

type StatusError struct {
	Code int
	Err  error
}

StatusError implements Error interface.

NewError

func NewError(code int, err error) StatusError

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

StatusError.Error

func (e StatusError) Error() string

Error implements error.Error.

StatusError.Status

func (e StatusError) Status() int

Status implements Error.Status.

Dependency graph