emir

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 5, 2021 License: MIT Imports: 18 Imported by: 1

README

emir

Build Status Go Report Card codecov Go Reference

A lightweight, high performance micro web framework.

It's based on FastHTTP and inspired by atreugo and echo.

Feature Overview

  • Based on fasthttp/router.
  • It's based on FastHTTP. It's faster up to 10 times faster than net/http.
  • Uses uber/zap.
  • Path parameters.
  • Multiple handlers to single route.
  • Before and after middlewares to a router or to a specific route.
  • Define an error handler to a router or to a specific route.
  • Data binding for JSON, XML, form and query payload.
  • Customizable Request Context.
  • Common HTTP responses like JSON, HTML, plain text.

Documentation

Index

Constants

View Source
const (
	// Authentication
	HeaderAuthorization      = "Authorization"
	HeaderProxyAuthenticate  = "Proxy-Authenticate"
	HeaderProxyAuthorization = "Proxy-Authorization"
	HeaderWWWAuthenticate    = "WWW-Authenticate"

	// Caching
	HeaderAge           = "Age"
	HeaderCacheControl  = "Cache-Control"
	HeaderClearSiteData = "Clear-Site-Data"
	HeaderExpires       = "Expires"
	HeaderPragma        = "Pragma"
	HeaderWarning       = "Warning"

	// Client hints
	HeaderAcceptCH         = "Accept-CH"
	HeaderAcceptCHLifetime = "Accept-CH-Lifetime"
	HeaderContentDPR       = "Content-DPR"
	HeaderDPR              = "DPR"
	HeaderEarlyData        = "Early-Data"
	HeaderSaveData         = "Save-Data"
	HeaderViewportWidth    = "Viewport-Width"
	HeaderWidth            = "Width"

	// Conditionals
	HeaderETag              = "ETag"
	HeaderIfMatch           = "If-Match"
	HeaderIfModifiedSince   = "If-Modified-Since"
	HeaderIfNoneMatch       = "If-None-Match"
	HeaderIfUnmodifiedSince = "If-Unmodified-Since"
	HeaderLastModified      = "Last-Modified"
	HeaderVary              = "Vary"

	// Connection management
	HeaderConnection = "Connection"
	HeaderKeepAlive  = "Keep-Alive"

	// Content negotiation
	HeaderAccept         = "Accept"
	HeaderAcceptCharset  = "Accept-Charset"
	HeaderAcceptEncoding = "Accept-Encoding"
	HeaderAcceptLanguage = "Accept-Language"

	// Controls
	HeaderCookie      = "Cookie"
	HeaderExpect      = "Expect"
	HeaderMaxForwards = "Max-Forwards"
	HeaderSetCookie   = "Set-Cookie"

	// CORS
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderOrigin                        = "Origin"
	HeaderTimingAllowOrigin             = "Timing-Allow-Origin"
	HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies"

	// Do Not Track
	HeaderDNT = "DNT"
	HeaderTk  = "Tk"

	// Downloads
	HeaderContentDisposition = "Content-Disposition"

	// Message body information
	HeaderContentEncoding = "Content-Encoding"
	HeaderContentLanguage = "Content-Language"
	HeaderContentLength   = "Content-Length"
	HeaderContentLocation = "Content-Location"
	HeaderContentType     = "Content-Type"

	// Proxies
	HeaderForwarded       = "Forwarded"
	HeaderVia             = "Via"
	HeaderXForwardedFor   = "X-Forwarded-For"
	HeaderXForwardedHost  = "X-Forwarded-Host"
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// Redirects
	HeaderLocation = "Location"

	// Request context
	HeaderFrom           = "From"
	HeaderHost           = "Host"
	HeaderReferer        = "Referer"
	HeaderReferrerPolicy = "Referrer-Policy"
	HeaderUserAgent      = "User-Agent"

	// Response context
	HeaderAllow  = "Allow"
	HeaderServer = "Server"

	// Range requests
	HeaderAcceptRanges = "Accept-Ranges"
	HeaderContentRange = "Content-Range"
	HeaderIfRange      = "If-Range"
	HeaderRange        = "Range"

	// Security
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderCrossOriginResourcePolicy       = "Cross-Origin-Resource-Policy"
	HeaderExpectCT                        = "Expect-CT"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXDownloadOptions                = "X-Download-Options"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXPoweredBy                      = "X-Powered-By"
	HeaderXXSSProtection                  = "X-XSS-Protection"

	// Server-sent event
	HeaderLastEventID = "Last-Event-ID"
	HeaderNEL         = "NEL"
	HeaderPingFrom    = "Ping-From"
	HeaderPingTo      = "Ping-To"
	HeaderReportTo    = "Report-To"

	// Transfer coding
	HeaderTE               = "TE"
	HeaderTrailer          = "Trailer"
	HeaderTransferEncoding = "Transfer-Encoding"

	// WebSockets
	HeaderSecWebSocketAccept     = "Sec-WebSocket-Accept"
	HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions"
	HeaderSecWebSocketKey        = "Sec-WebSocket-Key"
	HeaderSecWebSocketProtocol   = "Sec-WebSocket-Protocol"
	HeaderSecWebSocketVersion    = "Sec-WebSocket-Version"

	// Other
	HeaderAcceptPatch         = "Accept-Patch"
	HeaderAcceptPushPolicy    = "Accept-Push-Policy"
	HeaderAcceptSignature     = "Accept-Signature"
	HeaderAltSvc              = "Alt-Svc"
	HeaderDate                = "Date"
	HeaderIndex               = "Index"
	HeaderLargeAllocation     = "Large-Allocation"
	HeaderLink                = "Link"
	HeaderPushPolicy          = "Push-Policy"
	HeaderRetryAfter          = "Retry-After"
	HeaderServerTiming        = "Server-Timing"
	HeaderSignature           = "Signature"
	HeaderSignedHeaders       = "Signed-Headers"
	HeaderSourceMap           = "SourceMap"
	HeaderUpgrade             = "Upgrade"
	HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control"
	HeaderXPingback           = "X-Pingback"
	HeaderXRequestedWith      = "X-Requested-With"
	HeaderXRobotsTag          = "X-Robots-Tag"
	HeaderXUACompatible       = "X-UA-Compatible"
	HeaderXRequestID          = "X-Request-ID"
)

Headers

View Source
const (
	MethodGet     = "GET"     // RFC 7231, 4.3.1
	MethodHead    = "HEAD"    // RFC 7231, 4.3.2
	MethodPost    = "POST"    // RFC 7231, 4.3.3
	MethodPut     = "PUT"     // RFC 7231, 4.3.4
	MethodPatch   = "PATCH"   // RFC 5789
	MethodDelete  = "DELETE"  // RFC 7231, 4.3.5
	MethodConnect = "CONNECT" // RFC 7231, 4.3.6
	MethodOptions = "OPTIONS" // RFC 7231, 4.3.7
	MethodTrace   = "TRACE"   // RFC 7231, 4.3.8
)

HTTP methods were copied from net/http.

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes were stolen from net/http.

View Source
const (
	ContentTypeApplicationJSON = "application/json"
	ContentTypeApplicationXML  = "application/xml"
	ContentTypeApplicationForm = "application/x-www-form-urlencoded"
	ContentTypeTextXML         = "text/xml"
	ContentTypeTextHTML        = "text/html"
	ContentTypeTextPlain       = "text/plain"
)

Content Types

View Source
const (
	//DefaultNetwork is the default listen network
	DefaultNetwork = "tcp4"

	//DefaultAddress is the default listen address
	DefaultAddress = "localhost:8080"

	//DefaultServerName is the default server name
	DefaultServerName = "emir"

	//DefaultReadTimeout is the default read timeout
	DefaultReadTimeout = 20 * time.Second
)

Variables

This section is empty.

Functions

func B2S

func B2S(b []byte) string

B2S converts byte slice to a string without memory allocation. See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .

func ConvertArgsToValues

func ConvertArgsToValues(args *fasthttp.Args) url.Values

ConvertArgsToValues converts given fasthttp.Args to url.Values

func ConvertToFastHTTPHandler

func ConvertToFastHTTPHandler(handler RequestHandler) fasthttp.RequestHandler

ConvertToFastHTTPHandler wraps and converts the given handler to fasthttp.RequestHandler

func DefaultErrorHandler

func DefaultErrorHandler(ctx *Context, err error)

DefaultErrorHandler is the default error handler

func DefaultLogger

func DefaultLogger() *zap.Logger

DefaultLogger creates a empty development logger

func DefaultMethodNotAllowed

func DefaultMethodNotAllowed(c *Context) error

DefaultMethodNotAllowed is the default method not allowed handler

func DefaultNotFoundHandler

func DefaultNotFoundHandler(c *Context) error

DefaultNotFoundHandler is the default not found handler

func DefaultPanicHandler

func DefaultPanicHandler(c *Context, v interface{})

DefaultPanicHandler is the default panic handler

func NewBasicError

func NewBasicError(status int, errorMessage string, errorCode ...interface{}) error

NewBasicError returns an error instance that carries status, error message, and code

Returned error should be released after used If you are using a custom error handler, you should release BasicError instances

func ReleaseBasicError

func ReleaseBasicError(err *BasicError)

ReleaseBasicError returns acquired error instance to the error pool

It is forbidden accessing to the released error instance

func S2B

func S2B(s string) (b []byte)

S2B converts string to a byte slice without memory allocation.

Note it may break if string and/or slice header will change in the future go versions.

Types

type BasicError

type BasicError struct {
	StatusCode   int
	ErrorMessage string      `json:"message"`
	ErrorCode    interface{} `json:"code"`
}

BasicError represents an error that ocured while handling a request

func AcquireBasicError

func AcquireBasicError() *BasicError

AcquireBasicError returns an error instance from context pool The returned instance might be dirty You should set all fields before using

The returned error instancec may be passed to ReleaseBasicError when it is no longer needed It is forbidden accessing to the released error instance

func (*BasicError) Error

func (err *BasicError) Error() string

type Binder

type Binder interface {
	Bind(c *Context, v interface{}) error
}

Binder is the interface that wraps the Bind method.

type ComplexRequestHandler added in v0.0.4

type ComplexRequestHandler interface {
	Handle(*Context) error
}

type Config

type Config struct {
	Network     string
	Addr        string
	Compress    bool
	TLS         bool
	CertFile    string
	CertKeyFile string

	GracefulShutdown                   bool
	ErrorHandler                       ErrorHandler
	Logger                             *zap.Logger
	Name                               string
	Concurrency                        int
	DisableKeepalive                   bool
	ReadBufferSize                     int
	WriteBufferSize                    int
	ReadTimeout                        time.Duration
	WriteTimeout                       time.Duration
	IdleTimeout                        time.Duration
	MaxConnsPerIP                      int
	MaxRequestsPerConn                 int
	MaxKeepaliveDuration               time.Duration
	TCPKeepalive                       bool
	TCPKeepalivePeriod                 time.Duration
	MaxRequestBodySize                 int
	ReduceMemoryUsage                  bool
	GetOnly                            bool
	DisablePreParseMultipartForm       bool
	LogAllErrors                       bool
	DisableHeaderNamesNormalizing      bool
	SleepWhenConcurrencyLimitsExceeded time.Duration
	NoDefaultServerHeader              bool
	NoDefaultDate                      bool
	NoDefaultContentType               bool
	ConnState                          func(net.Conn, fasthttp.ConnState)
	KeepHijackedConns                  bool

	//Router settings
	SaveMatchedRoutePath   bool
	RedirectTrailingSlash  bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	HandleOPTIONS          bool
	GlobalOPTIONS          RequestHandler
	NotFound               RequestHandler
	MethodNotAllowed       RequestHandler
	PanicHandler           func(*Context, interface{})
}

Config carries configuration for FasthHTTP server and Router

type Context

type Context struct {
	*fasthttp.RequestCtx
	// contains filtered or unexported fields
}

Context context wrapper of fasthttp.RequestCtx to adds extra functionality

func (*Context) Bind

func (c *Context) Bind(v interface{}) error

Bind binds the request body into given value.

func (*Context) Emir

func (c *Context) Emir() *Emir

Emir returns the Emir instance

func (*Context) HTML

func (c *Context) HTML(v string, statusCode ...int) error

HTML sends a HTML response with given status code. Status code is optional.

func (*Context) HTMLBytes

func (c *Context) HTMLBytes(v []byte, statusCode ...int) error

HTMLBytes sends a HTML response with given status code. Status code is optional.

func (*Context) JSON

func (c *Context) JSON(v interface{}, statusCode ...int) error

JSON sends a JSON response with given status code. Status code is optional.

func (*Context) JSONMarshaler

func (c *Context) JSONMarshaler(v json.Marshaler, statusCode ...int) error

JSONMarshaler sends a JSON response with given status code. The value must be compatible with json.Marshaler interface. Status code is optional.

func (*Context) LogDPanic added in v0.0.4

func (c *Context) LogDPanic(msg string, fields ...zap.Field)

LogDPanic logs a message at DPanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger. If the logger is in development mode, it then panics (DPanic means "development panic"). This is useful for catching errors that are recoverable, but shouldn't ever happen.

func (*Context) LogDebug added in v0.0.4

func (c *Context) LogDebug(msg string, fields ...zap.Field)

LogDebug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Context) LogError added in v0.0.4

func (c *Context) LogError(msg string, fields ...zap.Field)

LogError logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Context) LogFatal added in v0.0.4

func (c *Context) LogFatal(msg string, fields ...zap.Field)

LogFatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Context) LogInfo added in v0.0.4

func (c *Context) LogInfo(msg string, fields ...zap.Field)

LogInfo logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Context) LogPanic added in v0.0.4

func (c *Context) LogPanic(msg string, fields ...zap.Field)

LogPanic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Context) LogWarn added in v0.0.4

func (c *Context) LogWarn(msg string, fields ...zap.Field)

LogWarn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*Context) Logger

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

Logger returns the logger.

func (*Context) Next

func (c *Context) Next() error

Next executes the next request handler.

func (*Context) PlainString

func (c *Context) PlainString(v string, statusCode ...int) error

PlainString sends a plain text response with given status code. Status code is optional

func (*Context) Query added in v0.0.4

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

Query returns query parameter by name.

func (*Context) ReqHeader

func (c *Context) ReqHeader() *fasthttp.RequestHeader

ReqHeader returns request headers.

func (*Context) ReqIDZap added in v0.0.4

func (c *Context) ReqIDZap() zap.Field

ReqIDZap returns the request id as zap.Field.

func (*Context) RequestID added in v0.0.4

func (c *Context) RequestID() []byte

RequestID returns the request id.

func (*Context) RespHeader

func (c *Context) RespHeader() *fasthttp.ResponseHeader

RespHeader returns response headers.

func (*Context) Route

func (c *Context) Route() *Route

Route returns the route instance

func (*Context) Validate

func (c *Context) Validate(v interface{}) error

Validate validates given value.

type DefaultBinder

type DefaultBinder struct {
}

DefaultBinder is the default implementation of the Binder interface.

func (*DefaultBinder) Bind

func (*DefaultBinder) Bind(c *Context, v interface{}) error

Bind implements the Binder#Bind function. Binding is done in following order: Binder will bind the body first then binds the query params If the request method is not POST, PUT or PATCH then the binder will skip the body Struct tag for query params will be "qs".

type Emir

type Emir struct {
	Logger *zap.Logger
	Router
	// contains filtered or unexported fields
}

Emir is the top-level framework instance

func New

func New(cfg Config) *Emir

New creates an instance of Emir

func (*Emir) Handler

func (e *Emir) Handler() fasthttp.RequestHandler

Handler returns router's request handler.

func (*Emir) ListenAndServe

func (e *Emir) ListenAndServe() error

ListenAndServe serves the server. It serves the server gracefully if #Config.GracefullShutdown is true

func (*Emir) NewVirtualHost

func (e *Emir) NewVirtualHost(hostname string) Router

NewVirtualHost creates a new router group for the provided hostname

func (*Emir) Serve

func (e *Emir) Serve(ln net.Listener) error

Serve serves the server with given listener.

func (*Emir) ServeGracefully

func (e *Emir) ServeGracefully(ln net.Listener) error

ServeGracefully serves gracefully the server with given listener.

func (*Emir) Shutdown

func (e *Emir) Shutdown() error

Shutdown shuts the server

type ErrorHandler

type ErrorHandler func(*Context, error)

ErrorHandler must process errror returned by RequestHandler.

type RequestHandler

type RequestHandler func(*Context) error

RequestHandler must process incoming requests

func ConvertFastHTTPHandler

func ConvertFastHTTPHandler(handler fasthttp.RequestHandler) RequestHandler

ConvertFastHTTPHandler converts given fasthttp.RequestHandler to RequestHandler

func ConvertStdHTTPHandler

func ConvertStdHTTPHandler(handler http.HandlerFunc) RequestHandler

ConvertStdHTTPHandler converts given http.HandlerFunc to RequestHandler

type Route

type Route struct {
	RouteName        string
	Path             string
	Method           string
	Middlewares      []RequestHandler
	Handlers         []RequestHandler
	AfterMiddlewares []RequestHandler
	ErrorHandler     ErrorHandler
	Binder           Binder
	Validator        Validator
}

Route represents a route in router It carries route's path, method, handlers, middlewares and error handlers.

func (*Route) After

func (r *Route) After(handler ...RequestHandler) *Route

After registers given handlers as middleware to the route Given handlers will be executed after the main handlers by the given order

func (*Route) Bind

func (r *Route) Bind(b Binder)

Bind registers given binder as binder to the route

func (*Route) Handle

func (r *Route) Handle(handler ...RequestHandler) *Route

Handle registers given handlers as main handler to the route Given handlers will be executed after "middlewares" and before the "after middlewares"

func (*Route) HandleError

func (r *Route) HandleError(handler ErrorHandler)

HandleError registers given error handlers as error handler to the route

func (*Route) Name added in v0.0.4

func (r *Route) Name(name string) *Route

Name sets route name

func (*Route) Use

func (r *Route) Use(handlers ...RequestHandler) *Route

Use registers given handlers as middleware to the route Given handlers will be executed by given order

func (*Route) Validate

func (r *Route) Validate(v Validator)

Validate registers given validator as validator to the route

type Router

type Router interface {
	// Handle registers given request handlers with the given path and method
	// There are shortcuts for some methods you can use them.
	Handle(path, method string, handlers ...RequestHandler) *Route

	// Use registers given middleware handlers to router
	// Given handlers will be executed by given order
	Use(handlers ...RequestHandler) Router

	// After registers given handlers to router
	After(handlers ...RequestHandler) Router

	// GET is a shortcut for router.Handle(fasthttp.MethodGet, path, handlers)
	GET(path string, handlers ...RequestHandler) *Route

	// POST is a shortcut for router.Handle(fasthttp.MethodPost, path, handlers)
	POST(path string, handlers ...RequestHandler) *Route

	// PUT is a shortcut for router.Handle(fasthttp.MethodPut, path, handlers)
	PUT(path string, handlers ...RequestHandler) *Route

	// PATCH is a shortcut for router.Handle(fasthttp.MethodPatch, path, handlers)
	PATCH(path string, handlers ...RequestHandler) *Route

	// DELETE is a shortcut for router.Handle(fasthttp.MethodDelete, path, handlers)
	DELETE(path string, handlers ...RequestHandler) *Route

	// HEAD is a shortcut for router.Handle(fasthttp.MethodHead, path, handlers)
	HEAD(path string, handlers ...RequestHandler) *Route

	// TRACE is a shortcut for router.Handle(fasthttp.MethodTrace, path, handlers)
	TRACE(path string, handlers ...RequestHandler) *Route

	// Handler gives routers request handler.
	// Returns un-nil function only if the router is a virtual host router.
	Handler() fasthttp.RequestHandler

	// NewGroup creates a subrouter for given path.
	NewGroup(path string) Router

	// Validate registers given validator to the router
	Validate(v Validator)

	// Bind registers given binder to the router
	Bind(b Binder)

	// HandleError registers given error handler to the router
	HandleError(handler ErrorHandler)
}

Router is the registry of all registered routes.

type Validator

type Validator interface {
	Validate(i interface{}) error
}

Validator is the interface that wraps the Validate method.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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