Documentation ¶
Index ¶
- Constants
- func B2S(b []byte) string
- func ConvertArgsToValues(args *fasthttp.Args) url.Values
- func ConvertToFastHTTPHandler(handler RequestHandler) fasthttp.RequestHandler
- func DefaultErrorHandler(ctx *Context, err error)
- func DefaultLogger() *zap.Logger
- func DefaultMethodNotAllowed(c *Context) error
- func DefaultNotFoundHandler(c *Context) error
- func DefaultPanicHandler(c *Context, v interface{})
- func NewBasicError(status int, errorMessage string, errorCode ...interface{}) error
- func ReleaseBasicError(err *BasicError)
- func S2B(s string) (b []byte)
- type BasicError
- type Binder
- type ComplexRequestHandler
- type Config
- type Context
- func (c *Context) Bind(v interface{}) error
- func (c *Context) Emir() *Emir
- func (c *Context) HTML(v string, statusCode ...int) error
- func (c *Context) HTMLBytes(v []byte, statusCode ...int) error
- func (c *Context) JSON(v interface{}, statusCode ...int) error
- func (c *Context) JSONMarshaler(v json.Marshaler, statusCode ...int) error
- func (c *Context) LogDPanic(msg string, fields ...zap.Field)
- func (c *Context) LogDebug(msg string, fields ...zap.Field)
- func (c *Context) LogError(msg string, fields ...zap.Field)
- func (c *Context) LogFatal(msg string, fields ...zap.Field)
- func (c *Context) LogInfo(msg string, fields ...zap.Field)
- func (c *Context) LogPanic(msg string, fields ...zap.Field)
- func (c *Context) LogWarn(msg string, fields ...zap.Field)
- func (c *Context) Logger() *zap.Logger
- func (c *Context) Next() error
- func (c *Context) PlainString(v string, statusCode ...int) error
- func (c *Context) Query(key string) string
- func (c *Context) ReqHeader() *fasthttp.RequestHeader
- func (c *Context) ReqIDZap() zap.Field
- func (c *Context) RequestID() []byte
- func (c *Context) RespHeader() *fasthttp.ResponseHeader
- func (c *Context) Route() *Route
- func (c *Context) Validate(v interface{}) error
- type DefaultBinder
- type Emir
- type ErrorHandler
- type RequestHandler
- type Route
- func (r *Route) After(handler ...RequestHandler) *Route
- func (r *Route) Bind(b Binder)
- func (r *Route) Handle(handler ...RequestHandler) *Route
- func (r *Route) HandleError(handler ErrorHandler)
- func (r *Route) Name(name string) *Route
- func (r *Route) Use(handlers ...RequestHandler) *Route
- func (r *Route) Validate(v Validator)
- type Router
- type Validator
Constants ¶
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
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.
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 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 StatusInternalServerError = 500 // RFC 7231, 6.6.1 StatusNotImplemented = 501 // RFC 7231, 6.6.2 StatusBadGateway = 502 // RFC 7231, 6.6.3 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.
const ( ContentTypeApplicationJSON = "application/json" ContentTypeApplicationXML = "application/xml" ContentTypeApplicationForm = "application/x-www-form-urlencoded" ContentTypeTextXML = "text/xml" ContentTypeTextHTML = "text/html" ContentTypeTextPlain = "text/plain" )
Content Types
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 ¶
B2S converts byte slice to a string without memory allocation. See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
func ConvertArgsToValues ¶
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 ¶
DefaultErrorHandler is the default error handler
func DefaultLogger ¶
DefaultLogger creates a empty development logger
func DefaultMethodNotAllowed ¶
DefaultMethodNotAllowed is the default method not allowed handler
func DefaultNotFoundHandler ¶
DefaultNotFoundHandler is the default not found handler
func DefaultPanicHandler ¶
func DefaultPanicHandler(c *Context, v interface{})
DefaultPanicHandler is the default panic handler
func NewBasicError ¶
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
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 ComplexRequestHandler ¶ added in v0.0.4
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) HTMLBytes ¶
HTMLBytes sends a HTML response with given status code. Status code is optional.
func (*Context) JSONMarshaler ¶
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
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
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
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
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
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
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
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) PlainString ¶
PlainString sends a plain text response with given status code. Status code is optional
func (*Context) ReqHeader ¶
func (c *Context) ReqHeader() *fasthttp.RequestHeader
ReqHeader returns request headers.
func (*Context) RespHeader ¶
func (c *Context) RespHeader() *fasthttp.ResponseHeader
RespHeader returns response headers.
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 ¶
Emir is the top-level framework instance
func (*Emir) Handler ¶
func (e *Emir) Handler() fasthttp.RequestHandler
Handler returns router's request handler.
func (*Emir) ListenAndServe ¶
ListenAndServe serves the server. It serves the server gracefully if #Config.GracefullShutdown is true
func (*Emir) NewVirtualHost ¶
NewVirtualHost creates a new router group for the provided hostname
func (*Emir) ServeGracefully ¶
ServeGracefully serves gracefully the server with given listener.
type ErrorHandler ¶
ErrorHandler must process errror returned by RequestHandler.
type RequestHandler ¶
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) 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) 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
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.