Documentation
¶
Index ¶
- Constants
- Variables
- func ErrorStatusCode(err error) int
- func HTTPErrorStatusCode(err error) int
- func ResponseCommitted(w http.ResponseWriter) bool
- func ResponseReaderFrom(w http.ResponseWriter) io.ReaderFrom
- func ResponseSize(w http.ResponseWriter) int64
- func ResponseStatusCode(w http.ResponseWriter) int
- type BeforeServeFunc
- type Committer
- type ErrorHandler
- type ErrorHandlerFunc
- type HTTPError
- type Handler
- type HandlerFunc
- type Middleware
- type Middlewares
- type RWUnwrapper
- type Route
- type Router
- func (r *Router) Build() http.Handler
- func (r *Router) BuildWithMux(mux *http.ServeMux) http.Handler
- func (r *Router) Patterns() iter.Seq[string]
- func (r *Router) Pre(middlewares ...*Middleware)
- func (r *Router) PreFunc(middlewareFuncs ...func(Handler) Handler)
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- type RouterGroup
- func (group *RouterGroup) Any(path string, handler Handler) *Route
- func (group *RouterGroup) DELETE(path string, handler Handler) *Route
- func (group *RouterGroup) GET(path string, handler Handler) *Route
- func (group *RouterGroup) Group(prefix string) *RouterGroup
- func (group *RouterGroup) HEAD(path string, handler Handler) *Route
- func (group *RouterGroup) OPTIONS(path string, handler Handler) *Route
- func (group *RouterGroup) PATCH(path string, handler Handler) *Route
- func (group *RouterGroup) POST(path string, handler Handler) *Route
- func (group *RouterGroup) PUT(path string, handler Handler) *Route
- func (group *RouterGroup) Route(method string, path string, handler Handler) *Route
- func (group *RouterGroup) SEARCH(path string, handler Handler) *Route
- func (group *RouterGroup) Use(middlewares ...*Middleware) *RouterGroup
- func (group *RouterGroup) UseFunc(middlewareFuncs ...func(Handler) Handler) *RouterGroup
- type Sizer
- type StatusCoder
Constants ¶
const ( CharsetUTF8 = "charset=UTF-8" XMLHTTPRequest = "XMLHttpRequest" IndexPage = "index.html" )
const ( // MIMEApplicationJSON JavaScript Object Notation (JSON) https://www.rfc-editor.org/rfc/rfc8259 MIMEApplicationJSON = "application/json" 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" MIMEEventStream = "text/event-stream" MIMEApplicationZip = "application/zip" )
MIME types
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" // HeaderAllow is the name of the "Allow" header field used to list the set of methods // advertised as supported by the target resource. Returning an Allow header is mandatory // for Status 405 (method not found) and useful for the OPTIONS method in responses. // See RFC 7231: https://datatracker.ietf.org/doc/html/rfc7231#section-7.4.1 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" HeaderRetryAfter = "Retry-After" 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" HeaderXCorrelationID = "X-Correlation-Id" HeaderXRequestedWith = "X-Requested-With" HeaderServer = "Server" HeaderOrigin = "Origin" HeaderCacheControl = "Cache-Control" HeaderConnection = "Connection" HeaderXRobotsTag = "X-Robots-Tag" HeaderXRateLimitLimit = "X-RateLimit-Limit" HeaderXRateLimitRemaining = "X-RateLimit-Remaining" HeaderXRateLimitReset = "X-RateLimit-Reset" // Access control 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" // Security 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" // Cloudflare // https://developers.cloudflare.com/fundamentals/reference/http-headers/#cf-ipcountry HeaderCFIPCountry = "CF-IPCountry" )
Headers
Variables ¶
var ( ErrBadRequest = &httpError{http.StatusBadRequest} // HTTP 400 Bad Request ErrPaymentRequired = &httpError{http.StatusPaymentRequired} // HTTP 402 Payment Required ErrForbidden = &httpError{http.StatusForbidden} // HTTP 403 Forbidden ErrNotFound = &httpError{http.StatusNotFound} // HTTP 404 Not Found ErrMethodNotAllowed = &httpError{http.StatusMethodNotAllowed} // HTTP 405 Method Not Allowed ErrNotAcceptable = &httpError{http.StatusNotAcceptable} // HTTP 406 Not Acceptable ErrProxyAuthRequired = &httpError{http.StatusProxyAuthRequired} // HTTP 407 Proxy AuthRequired ErrRequestTimeout = &httpError{http.StatusRequestTimeout} // HTTP 408 Request Timeout ErrConflict = &httpError{http.StatusConflict} // HTTP 409 Conflict ErrGone = &httpError{http.StatusGone} // HTTP 410 Gone ErrLengthRequired = &httpError{http.StatusLengthRequired} // HTTP 411 Length Required ErrPreconditionFailed = &httpError{http.StatusPreconditionFailed} // HTTP 412 Precondition Failed ErrRequestEntityTooLarge = &httpError{http.StatusRequestEntityTooLarge} // HTTP 413 Payload Too Large ErrRequestURITooLong = &httpError{http.StatusRequestURITooLong} // HTTP 414 URI Too Long ErrUnsupportedMediaType = &httpError{http.StatusUnsupportedMediaType} // HTTP 415 Unsupported Media Type ErrRequestedRangeNotSatisfiable = &httpError{http.StatusRequestedRangeNotSatisfiable} // HTTP 416 Range Not Satisfiable ErrExpectationFailed = &httpError{http.StatusExpectationFailed} // HTTP 417 Expectation Failed ErrTeapot = &httpError{http.StatusTeapot} // HTTP 418 I'm a teapot ErrMisdirectedRequest = &httpError{http.StatusMisdirectedRequest} // HTTP 421 Misdirected Request ErrUnprocessableEntity = &httpError{http.StatusUnprocessableEntity} // HTTP 422 Unprocessable Entity ErrLocked = &httpError{http.StatusLocked} // HTTP 423 Locked ErrFailedDependency = &httpError{http.StatusFailedDependency} // HTTP 424 Failed Dependency ErrTooEarly = &httpError{http.StatusTooEarly} // HTTP 425 Too Early ErrUpgradeRequired = &httpError{http.StatusUpgradeRequired} // HTTP 426 Upgrade Required ErrPreconditionRequired = &httpError{http.StatusPreconditionRequired} // HTTP 428 Precondition Required ErrTooManyRequests = &httpError{http.StatusTooManyRequests} // HTTP 429 Too Many Requests ErrRequestHeaderFieldsTooLarge = &httpError{http.StatusRequestHeaderFieldsTooLarge} // HTTP 431 Request Header Fields Too Large ErrInternalServerError = &httpError{http.StatusInternalServerError} // HTTP 500 Internal Server Error ErrNotImplemented = &httpError{http.StatusNotImplemented} // HTTP 501 Not Implemented ErrBadGateway = &httpError{http.StatusBadGateway} // HTTP 502 Bad Gateway ErrGatewayTimeout = &httpError{http.StatusGatewayTimeout} // HTTP 504 Gateway Timeout ErrHTTPVersionNotSupported = &httpError{http.StatusHTTPVersionNotSupported} // HTTP 505 HTTP Version Not Supported ErrVariantAlsoNegotiates = &httpError{http.StatusVariantAlsoNegotiates} // HTTP 506 Variant Also Negotiates ErrInsufficientStorage = &httpError{http.StatusInsufficientStorage} // HTTP 507 Insufficient Storage ErrLoopDetected = &httpError{http.StatusLoopDetected} // HTTP 508 Loop Detected ErrNotExtended = &httpError{http.StatusNotExtended} // HTTP 510 Not Extended ErrNetworkAuthenticationRequired = &httpError{http.StatusNetworkAuthenticationRequired} // HTTP 511 Network Authentication Required )
Following errors can produce HTTP status code by implementing HTTPStatusCoder interface
var ErrFileNotFound = ErrNotFound.Wrap(errors.New("file not found"))
Functions ¶
func ErrorStatusCode ¶
func HTTPErrorStatusCode ¶
func ResponseCommitted ¶
func ResponseCommitted(w http.ResponseWriter) bool
func ResponseReaderFrom ¶
func ResponseReaderFrom(w http.ResponseWriter) io.ReaderFrom
func ResponseSize ¶
func ResponseSize(w http.ResponseWriter) int64
func ResponseStatusCode ¶
func ResponseStatusCode(w http.ResponseWriter) int
Types ¶
type BeforeServeFunc ¶
func Attachment ¶
func Attachment(name string) BeforeServeFunc
Attachment set header to send a response as attachment, prompting client to save the file.
func CacheControl ¶
func CacheControl(data ...string) BeforeServeFunc
func ContentSecurityPolicy ¶
func ContentSecurityPolicy(data ...string) BeforeServeFunc
func Inline ¶
func Inline(name string) BeforeServeFunc
Inline set header to send a response as inline, opening the file in the browser.
type Committer ¶
type Committer interface {
Committed() bool
}
func ResponseCommitter ¶
func ResponseCommitter(w http.ResponseWriter) Committer
type ErrorHandler ¶
type ErrorHandler interface {
ServeHTTP(http.ResponseWriter, *http.Request, error)
}
type ErrorHandlerFunc ¶
type ErrorHandlerFunc func(http.ResponseWriter, *http.Request, error)
func (ErrorHandlerFunc) ServeHTTP ¶
func (f ErrorHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, e error)
type HTTPError ¶
type HTTPError struct {
Code int `json:"-"`
Message string `json:"message"`
// contains filtered or unexported fields
}
func NewHTTPError ¶
NewHTTPError creates a new instance of HTTPError
func (*HTTPError) StatusCode ¶
StatusCode returns status code for HTTP response
type Handler ¶
type Handler interface {
ServeHTTP(http.ResponseWriter, *http.Request) error
}
func FileFS ¶
func FileFS(fsys fs.FS, filename string, beforeServe ...BeforeServeFunc) Handler
FileFS serves the specified filename from fsys.
func StaticFS ¶
StaticFS serve static directory content from fsys.
If a file resource is missing and indexFallback is set, the request will be forwarded to the base index.html (useful for SPA with pretty urls).
Special redirects:
- if "path" is a file that ends in index.html, it is redirected to its non-index.html version (eg. /test/index.html -> /test/)
- if "path" is a directory that has index.html, the index.html file is rendered, otherwise if missing - returns ErrFileNotFound or fallback to the root index.html if indexFallback is set
Example:
fsys := os.DirFS("./public")
router.GET("/files/{path...}", StaticFS(fsys, "path", false))
type HandlerFunc ¶
type HandlerFunc func(http.ResponseWriter, *http.Request) error
func (HandlerFunc) ServeHTTP ¶
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) error
type Middlewares ¶
type Middlewares []*Middleware
type RWUnwrapper ¶
type RWUnwrapper interface {
Unwrap() http.ResponseWriter
}
RWUnwrapper specifies that a http.ResponseWriter could be "unwrapped" (usually used with http.ResponseController).
type Route ¶
type Route struct {
Method string
Path string
Handler Handler
Middlewares Middlewares
}
func (*Route) Use ¶
func (route *Route) Use(middlewares ...*Middleware) *Route
Use registers one or multiple middleware handlers to the current route.
func (*Route) UseFunc ¶
UseFunc registers one or multiple middleware functions to the current route.
The registered middleware functions are "anonymous" and with default priority, aka. executes in the order they were registered.
If you need to specify a named middleware or middleware with custom exec prirority, use the Route.Use method.
type Router ¶
type Router struct {
*RouterGroup
PreMiddlewares Middlewares
// contains filtered or unexported fields
}
func NewRouter ¶
func NewRouter(errorHandler ErrorHandler) *Router
func (*Router) Patterns ¶
Patterns returns a sequence of all route patterns currently registered in the router as strings.
func (*Router) Pre ¶
func (r *Router) Pre(middlewares ...*Middleware)
Pre registers one or multiple middleware handlers which are run before router tries to find matching route.
func (*Router) PreFunc ¶
PreFunc registers one or multiple middleware functions which are run before router tries to find matching route.
The registered middleware functions are "anonymous" and with default priority, aka. executes in the order they were registered.
If you need to specify a named middleware or middleware with custom exec priority, use Router.Pre method.
type RouterGroup ¶
type RouterGroup struct {
Prefix string
Middlewares Middlewares
// contains filtered or unexported fields
}
func (*RouterGroup) Any ¶
func (group *RouterGroup) Any(path string, handler Handler) *Route
Any is a shorthand for RouterGroup.Route with "" as route method (aka. matches any method).
func (*RouterGroup) DELETE ¶
func (group *RouterGroup) DELETE(path string, handler Handler) *Route
DELETE is a shorthand for RouterGroup.Route with DELETE as route method.
func (*RouterGroup) GET ¶
func (group *RouterGroup) GET(path string, handler Handler) *Route
GET is a shorthand for RouterGroup.Route with GET as route method.
func (*RouterGroup) Group ¶
func (group *RouterGroup) Group(prefix string) *RouterGroup
Group creates and register a new child RouterGroup into the current one with the specified prefix.
The prefix follows the standard Go net/http http.ServeMux pattern format ("[HOST]/[PATH]") and will be concatenated recursively into the final route path, meaning that only the root level group could have HOST as part of the prefix.
Returns the newly created group to allow chaining and registering sub-routes and group specific middlewares.
func (*RouterGroup) HEAD ¶
func (group *RouterGroup) HEAD(path string, handler Handler) *Route
HEAD is a shorthand for RouterGroup.Route with HEAD as route method.
func (*RouterGroup) OPTIONS ¶
func (group *RouterGroup) OPTIONS(path string, handler Handler) *Route
OPTIONS is a shorthand for RouterGroup.Route with OPTIONS as route method.
func (*RouterGroup) PATCH ¶
func (group *RouterGroup) PATCH(path string, handler Handler) *Route
PATCH is a shorthand for RouterGroup.Route with PATCH as route method.
func (*RouterGroup) POST ¶
func (group *RouterGroup) POST(path string, handler Handler) *Route
POST is a shorthand for RouterGroup.Route with POST as route method.
func (*RouterGroup) PUT ¶
func (group *RouterGroup) PUT(path string, handler Handler) *Route
PUT is a shorthand for RouterGroup.Route with PUT as route method.
func (*RouterGroup) Route ¶
func (group *RouterGroup) Route(method string, path string, handler Handler) *Route
Route registers a single route into the current group.
Note that the final route path will be the concatenation of all parent groups prefixes + the route path. The path follows the standard Go net/http http.ServeMux format ("[HOST]/[PATH]"), meaning that only a top level group route could have HOST as part of the prefix.
Returns the newly created route to allow attaching route-only middlewares.
func (*RouterGroup) SEARCH ¶
func (group *RouterGroup) SEARCH(path string, handler Handler) *Route
SEARCH is a shorthand for RouterGroup.Route with SEARCH as route method.
func (*RouterGroup) Use ¶
func (group *RouterGroup) Use(middlewares ...*Middleware) *RouterGroup
Use registers one or multiple middleware handlers to the current group.
func (*RouterGroup) UseFunc ¶
func (group *RouterGroup) UseFunc(middlewareFuncs ...func(Handler) Handler) *RouterGroup
UseFunc registers one or multiple middleware functions to the current group.
The registered middleware functions are "anonymous" and with default priority, aka. executes in the order they were registered.
If you need to specify a named middleware or middleware with custom exec priority, use RouterGroup.Use method.
type Sizer ¶
type Sizer interface {
Size() int64
}
func ResponseSizer ¶
func ResponseSizer(w http.ResponseWriter) Sizer
type StatusCoder ¶
type StatusCoder interface {
StatusCode() int
}
func ResponseStatusCoder ¶
func ResponseStatusCoder(w http.ResponseWriter) StatusCoder