Documentation ¶
Index ¶
- Constants
- Variables
- func StatusText(code int) string
- func Stringify(b []byte) string
- type Context
- type Error
- type ErrorHandler
- type Fields
- type HandlerFunc
- type Mux
- func (m *Mux) CONNECT(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) DELETE(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) GET(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) Group(prefix string, routes []*Route) []*Route
- func (m *Mux) HEAD(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) NotFound(handlers ...HandlerFunc)
- func (m *Mux) OPTIONS(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) PATCH(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) POST(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) PUT(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) Start(addr string) error
- func (m *Mux) Static(prefix, root string)
- func (m *Mux) Stop() error
- func (m *Mux) TRACE(path string, handlers ...HandlerFunc) *Route
- func (m *Mux) Use(middlewares ...HandlerFunc)
- type Muxer
- type Network
- type Options
- type Route
Constants ¶
const ( MIMEApplicationJSON = "application/json" MIMEApplicationJSONCharsetUTF8 = MIMEApplicationJSON + "; " + charsetUTF8 MIMEApplicationJavaScript = "application/javascript" MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8 MIMEApplicationXML = "application/xml" MIMEApplicationXMLCharsetUTF8 = MIMEApplicationXML + "; " + charsetUTF8 MIMETextXML = "text/xml" MIMETextXMLCharsetUTF8 = MIMETextXML + "; " + charsetUTF8 MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEApplicationProtobuf = "application/protobuf" MIMEApplicationMsgpack = "application/msgpack" MIMETextHTML = "text/html" MIMETextHTMLCharsetUTF8 = MIMETextHTML + "; " + charsetUTF8 MIMETextPlain = "text/plain" MIMETextPlainCharsetUTF8 = MIMETextPlain + "; " + charsetUTF8 MIMEMultipartForm = "multipart/form-data" MIMEOctetStream = "application/octet-stream" )
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAllow = "Allow" HeaderAuthorization = "Authorization" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLength = "Content-Length" HeaderContentType = "Content-Type" HeaderCookie = "Cookie" HeaderSetCookie = "Set-Cookie" HeaderIfModifiedSince = "If-Modified-Since" HeaderLastModified = "Last-Modified" HeaderLocation = "Location" HeaderUpgrade = "Upgrade" HeaderVary = "Vary" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderXHTTPMethodOverride = "X-HTTP-Method-Override" HeaderXRealIP = "X-Real-IP" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" HeaderAccessControlRequestMethod = "Access-Control-Request-Method" HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers" HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin" HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods" HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers" HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials" HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers" HeaderAccessControlMaxAge = "Access-Control-Max-Age" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXXSSProtection = "X-XSS-Protection" HeaderXFrameOptions = "X-Frame-Options" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderXCSRFToken = "X-CSRF-Token" HeaderReferrerPolicy = "Referrer-Policy" )
const ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" // RFC 5789 MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE" )
Common HTTP methods.
Unless otherwise noted, these are defined in RFC 7231 section 4.3.
const ( // Version holds the semantic version of Muxer Version = "1.0.0" // DefaultBanner for Muxer DefaultBanner = `` /* 176-byte string literal not displayed */ )
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 StatusTooEarly = 425 // RFC 8470, 5.2. 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 as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
Variables ¶
var ( ErrBadRequest = NewError(StatusBadRequest) // RFC 7231, 6.5.1 ErrMethodNotAllowed = NewError(StatusMethodNotAllowed) // RFC 7231, 6.5.5 ErrRequestTimeout = NewError(StatusRequestTimeout) // RFC 7231, 6.5.7 ErrRequestEntityTooLarge = NewError(StatusRequestEntityTooLarge) // RFC 7231, 6.5.11 ErrRequestHeaderFieldsTooLarge = NewError(StatusRequestHeaderFieldsTooLarge) // RFC 6585, 5 )
var DefaultErrorHandler = func(ctx Context, err error) error { code := StatusInternalServerError if e, ok := err.(*Error); ok { code = e.Code } ctx.SetHeader(HeaderContentType, MIMETextPlainCharsetUTF8) ctx.Status(code).SendString(err.Error()) return nil }
DefaultErrorHandler that process return errors from handlers
var DefaultOptions = &Options{ DisableBanner: false, DisableRouterPrinting: false, LRUCacheSize: defaultLRUCacheSize, Concurrency: defaultConcurrency, MaxRequestBodySize: defaultMaxRequestBodySize, MaxRouteParams: defaultMaxRouteParams, MaxRequestUrlLength: defaultMaxRequestUrlLength, Network: NetworkTCP4, ErrorHandler: DefaultErrorHandler, }
DefaultOptions provides the default options for Muxer,
Options:
- DisableBanner: false
- DisableRouterPrinting: false
- LRUCacheSize: 1024
- Concurrency: 256 * 1024
- MaxRequestBodySize: 4 * 1024 * 1024
- MaxRouteParams: 1024
- MaxRequestUrlLength: 2048
- Network: NetworkTCP4
Functions ¶
func StatusText ¶
StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.
Types ¶
type Context ¶
type Context interface { // Next passing to next handler/middleware, // Next should be used only inside middleware functions, // It executes the pending handler's in the chain inside the // calling handler Next() error // RawContext returns the fasthttp.RequestCtx instance // corresponding to this Context RawContext() *fasthttp.RequestCtx // Param returns value of the URL param Param(key string) string // Query returns the keyed url query value if it exist Query(key string) string // SendBytes with given bytes into the response body SendBytes(bytes []byte) Context // SendString with given string into the response body SendString(str string) Context // SendJSON with given interface{} with JSON serialized // format into response body SendJSON(in interface{}) error // Status sets the HTTP response code Status(status int) Context // SetHeader in the response. if value == "", // this method removes the header with given key SetHeader(key string, val string) // Header returns header value with given key in // request Header(key string) string // Set user data into context with given // key and val (type interface{}) as key/value // pair Set(key string, val interface{}) // Local returns the user data with given key Local(key string) interface{} // Body returns the body string from request Body() string // Method returns the request HTTP method as string Method() string }
Context contains incoming request and manages outgoing response,
It's forbidden copying Context instances.
Context is the most important part of Muxer, It allows us to pass variables between middleware, Context in Muxer is just the wrapper for fasthttp.RequestCtx
type Error ¶ added in v0.1.1
Error represents an error that occurred while handling a request.
type ErrorHandler ¶ added in v0.1.1
ErrorHandler represent a handler function to handling the error
type Fields ¶
type Fields map[string]interface{}
Fields is wrapper type for map[string]interface{}, useful for returning JSON data
type HandlerFunc ¶
HandlerFunc represent a handler function or middleware function of specific route
type Mux ¶ added in v0.1.1
type Mux struct {
// contains filtered or unexported fields
}
func (*Mux) CONNECT ¶ added in v0.1.1
func (m *Mux) CONNECT(path string, handlers ...HandlerFunc) *Route
CONNECT registers an http relevant method
func (*Mux) DELETE ¶ added in v0.1.1
func (m *Mux) DELETE(path string, handlers ...HandlerFunc) *Route
DELETE registers an http relevant method
func (*Mux) GET ¶ added in v0.1.1
func (m *Mux) GET(path string, handlers ...HandlerFunc) *Route
GET registers an http relevant method
func (*Mux) HEAD ¶ added in v0.1.1
func (m *Mux) HEAD(path string, handlers ...HandlerFunc) *Route
HEAD registers an http relevant method
func (*Mux) NotFound ¶ added in v0.1.1
func (m *Mux) NotFound(handlers ...HandlerFunc)
NotFound registers an http handlers that will be called when no other routes match with request
func (*Mux) OPTIONS ¶ added in v0.1.1
func (m *Mux) OPTIONS(path string, handlers ...HandlerFunc) *Route
OPTIONS registers an http relevant method
func (*Mux) PATCH ¶ added in v0.1.1
func (m *Mux) PATCH(path string, handlers ...HandlerFunc) *Route
PATCH registers an http relevant method
func (*Mux) POST ¶ added in v0.1.1
func (m *Mux) POST(path string, handlers ...HandlerFunc) *Route
POST registers an http relevant method
func (*Mux) PUT ¶ added in v0.1.1
func (m *Mux) PUT(path string, handlers ...HandlerFunc) *Route
PUT registers an http relevant method
func (*Mux) Start ¶ added in v0.1.1
Start the Muxer and dispatches the request to the handler whose pattern most closely matches the request URL.
func (*Mux) Stop ¶ added in v0.1.1
Stop the Muxer, release related resources and free used memories.
func (*Mux) TRACE ¶ added in v0.1.1
func (m *Mux) TRACE(path string, handlers ...HandlerFunc) *Route
TRACE registers an http relevant method
func (*Mux) Use ¶ added in v0.1.1
func (m *Mux) Use(middlewares ...HandlerFunc)
Use given middlewares for each route
type Muxer ¶
type Muxer interface { // Start the Muxer and dispatches the request // to the handler whose pattern most closely matches // the request URL. Start(addr string) error // Stop the Muxer, release related resources and free // used memories. Stop() error // Group the given routes with specific prefix Group(prefix string, routes []*Route) []*Route // Static serve files in root directory under specific prefix Static(prefix, root string) // NotFound registers an http handlers that will be called when // no other routes match with request NotFound(handlers ...HandlerFunc) // Use given middlewares for each route Use(middlewares ...HandlerFunc) // HEAD registers an http relevant method HEAD(path string, handlers ...HandlerFunc) *Route // GET registers an http relevant method GET(path string, handlers ...HandlerFunc) *Route // POST registers an http relevant method POST(path string, handlers ...HandlerFunc) *Route // PUT registers an http relevant method PUT(path string, handlers ...HandlerFunc) *Route // PATCH registers an http relevant method PATCH(path string, handlers ...HandlerFunc) *Route // DELETE registers an http relevant method DELETE(path string, handlers ...HandlerFunc) *Route // CONNECT registers an http relevant method CONNECT(path string, handlers ...HandlerFunc) *Route // OPTIONS registers an http relevant method OPTIONS(path string, handlers ...HandlerFunc) *Route // TRACE registers an http relevant method TRACE(path string, handlers ...HandlerFunc) *Route }
Muxer is an HTTP request multiplexer, It matches the URL of each incoming request against a prefix tree of registered routes and call the handler function for the route that most closely matches the URL.
type Options ¶
type Options struct { // DisableBanner printing for Muxer // // Default: true DisableBanner bool `json:"disable_banner"` // DisableRouterPrinting for Muxer // // Default: true DisableRouterPrinting bool `json:"disable_router_printing"` // CaseInsensitive routing when set true // // Default: false CaseInsensitive bool `json:"case_insensitive"` // DisableLRUCaching used to speeding up routing // // Default: false DisableLRUCaching bool `json:"disable_lru_caching"` // LRUCacheSize for LRU Cache used to speeding up routing, // only effective when `DisableLRUCaching` is not true // // Default: 1024 LRUCacheSize int `json:"lru_cache_size"` // AutoRecovering from panic while executing handlers by answering with // HTTP status code 500 and logging error message without unexpected server stopped // // Default: false AutoRecovering bool `json:"auto_recovering"` // ServerIdentifier for sending in response headers // // Default: "" ServerIdentifier string `json:"server_identifier"` // Concurrency holds the maximum number of concurrent connections // // Default: 256 * 1024 = 262144 Concurrency int `json:"concurrency"` // PreForkEnabled will spawn multiple Go processes listening // on the same port when set is true // // Default: false PreForkEnabled bool `json:"pre_fork_enabled"` // TLSEnabled when set is true // // Default: false TLSEnabled bool `json:"tls_enabled"` // TLSCertPath holds the certificate file path used to TLS // // Default: "" TLSCertPath string `json:"tls_cert_path"` // TLSKeyPath holds the key file path used to TLS // // Default: "" TLSKeyPath string `json:"tls_key_path"` // HandlerMethodNotAllowed enable answering with HTTP // status code 405 if request does not match with any // route, but there are another methods are allowed for // the route otherwise answer with Not Found handlers or // status code 404 // // Default: false HandlerMethodNotAllowed bool `json:"handler_method_not_allowed"` // HandlerOPTIONS enable automatic replies to OPTIONS request if // there are no handlers registered for that route // // Default: false HandlerOPTIONS bool `json:"handler_options"` // DisabledKeepalive disabled the keep-alive connections, the server // will close incoming connections after sending the first // response to client // // Default: false DisabledKeepalive bool `json:"disabled_keepalive"` // MaxRequestBodySize holds the maximum body size // // Default: 4 * 1024 * 1024 MaxRequestBodySize int `json:"max_request_body_size"` // MaxRouteParams holds the maximum params number for each route // // Default: 1024 MaxRouteParams int `json:"max_route_params"` // MaxRequestUrlLength holds the maximum url length for each request // // Default: 2048 MaxRequestUrlLength int `json:"max_request_url_length"` // ReadTimeout holds the amount of time allowed to read the full request // includes body // // Default: 0 (represent unlimited) ReadTimeout time.Duration `json:"read_timeout"` // WriteTimeout holds the duration before timing out writes of the response // // Default: 0 (represent unlimited) WriteTimeout time.Duration `json:"write_timeout"` // HttpIdleTimeout holds the maximum amount of time to wait for the next request // when DisabledKeepalive set is true // // Default: 0 (represent unlimited) HttpIdleTimeout time.Duration `json:"http_idle_timeout"` // Network holds the server TCP protocol version, // // WARNING: if the PreForkEnabled set is true, only // "tcp4" or "tcp6" can be choose // // Default: NetworkTCP4 Network Network `json:"network"` ErrorHandler ErrorHandler `json:"-"` }
Options holds the all supported Muxer options