Documentation
¶
Index ¶
- Constants
- Variables
- func Bind(r *http.Request, i interface{}) (err error)
- func BindBody(req *http.Request, i interface{}) (err error)
- func BindHeaders(r *http.Request, i interface{}) error
- func BindPathParams(r *http.Request, i interface{}) error
- func BindQueryParams(r *http.Request, i interface{}) error
- func DefaultErrHandlerFunc(err error, w http.ResponseWriter)
- func HTML(w http.ResponseWriter, statusCode int, html string) error
- func JSON(w http.ResponseWriter, statusCode int, data any) error
- func String(w http.ResponseWriter, statusCode int, s string) error
- func XML(w http.ResponseWriter, statusCode int, data any, indent string) error
- type ErrHandlerFunc
- type HTTPError
- type HandlerFunc
- type HelperResponseWriter
- func (rw *HelperResponseWriter) Flush()
- func (rw *HelperResponseWriter) HTML(statusCode int, html string) error
- func (rw *HelperResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
- func (rw *HelperResponseWriter) JSON(statusCode int, data any) error
- func (rw *HelperResponseWriter) Push(target string, opts *http.PushOptions) error
- func (rw *HelperResponseWriter) String(statusCode int, s string) error
- func (rw *HelperResponseWriter) Unwrap() http.ResponseWriter
- func (rw *HelperResponseWriter) XML(statusCode int, data any, indent string) error
- type Map
- type MiddlewareFunc
- type RouteMiddlewareFunc
- type ServeMux
- func (sm *ServeMux) Connect(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Delete(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Get(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Group(prefix string) *ServeMux
- func (sm *ServeMux) HandleFunc(pattern string, h HandlerFunc)
- func (sm *ServeMux) Head(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Options(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Patch(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Post(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Put(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (sm *ServeMux) Trace(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
- func (sm *ServeMux) Use(m ...MiddlewareFunc)
Constants ¶
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" MIMETextEventStream = "text/event-stream" MIMEXNDJSON = "application/x-ndjson" )
MIME types
const ( // PROPFIND Method can be used on collection and property resources. PROPFIND = "PROPFIND" // REPORT Method can be used to get information about a resource, see rfc 3253 REPORT = "REPORT" // RouteNotFound is special method type for routes handling "route not found" (404) cases RouteNotFound = "echo_route_not_found" )
const ( HeaderAccept = "Accept" HeaderAcceptEncoding = "Accept-Encoding" // 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" // 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" )
Headers
Variables ¶
var ( ErrBadRequest = NewHTTPError(helper(http.StatusBadRequest)) // HTTP 400 Bad Request ErrPaymentRequired = NewHTTPError(helper(http.StatusPaymentRequired)) // HTTP 402 Payment Required ErrForbidden = NewHTTPError(helper(http.StatusForbidden)) // HTTP 403 Forbidden ErrNotFound = NewHTTPError(helper(http.StatusNotFound)) // HTTP 404 Not Found ErrMethodNotAllowed = NewHTTPError(helper(http.StatusMethodNotAllowed)) // HTTP 405 Method Not Allowed ErrNotAcceptable = NewHTTPError(helper(http.StatusNotAcceptable)) // HTTP 406 Not Acceptable ErrProxyAuthRequired = NewHTTPError(helper(http.StatusProxyAuthRequired)) // HTTP 407 Proxy AuthRequired ErrRequestTimeout = NewHTTPError(helper(http.StatusRequestTimeout)) // HTTP 408 Request Timeout ErrConflict = NewHTTPError(helper(http.StatusConflict)) // HTTP 409 Conflict ErrGone = NewHTTPError(helper(http.StatusGone)) // HTTP 410 Gone ErrLengthRequired = NewHTTPError(helper(http.StatusLengthRequired)) // HTTP 411 Length Required ErrPreconditionFailed = NewHTTPError(helper(http.StatusPreconditionFailed)) // HTTP 412 Precondition Failed ErrStatusRequestEntityTooLarge = NewHTTPError(helper(http.StatusRequestEntityTooLarge)) // HTTP 413 Payload Too Large ErrRequestURITooLong = NewHTTPError(helper(http.StatusRequestURITooLong)) // HTTP 414 URI Too Long ErrUnsupportedMediaType = NewHTTPError(helper(http.StatusUnsupportedMediaType)) // HTTP 415 Unsupported Media Type ErrRequestedRangeNotSatisfiable = NewHTTPError(helper(http.StatusRequestedRangeNotSatisfiable)) // HTTP 416 Range Not Satisfiable ErrExpectationFailed = NewHTTPError(helper(http.StatusExpectationFailed)) // HTTP 417 Expectation Failed ErrTeapot = NewHTTPError(helper(http.StatusTeapot)) // HTTP 418 I'm a teapot ErrMisdirectedRequest = NewHTTPError(helper(http.StatusMisdirectedRequest)) // HTTP 421 Misdirected Request ErrUnprocessableEntity = NewHTTPError(helper(http.StatusUnprocessableEntity)) // HTTP 422 Unprocessable Entity ErrLocked = NewHTTPError(helper(http.StatusLocked)) // HTTP 423 Locked ErrFailedDependency = NewHTTPError(helper(http.StatusFailedDependency)) // HTTP 424 Failed Dependency ErrTooEarly = NewHTTPError(helper(http.StatusTooEarly)) // HTTP 425 Too Early ErrUpgradeRequired = NewHTTPError(helper(http.StatusUpgradeRequired)) // HTTP 426 Upgrade Required ErrPreconditionRequired = NewHTTPError(helper(http.StatusPreconditionRequired)) // HTTP 428 Precondition Required ErrTooManyRequests = NewHTTPError(helper(http.StatusTooManyRequests)) // HTTP 429 Too Many Requests ErrRequestHeaderFieldsTooLarge = NewHTTPError(helper(http.StatusRequestHeaderFieldsTooLarge)) // HTTP 431 Request Header Fields Too Large ErrInternalServerError = NewHTTPError(helper(http.StatusInternalServerError)) // HTTP 500 Internal Server Error ErrNotImplemented = NewHTTPError(helper(http.StatusNotImplemented)) // HTTP 501 Not Implemented ErrBadGateway = NewHTTPError(helper(http.StatusBadGateway)) // HTTP 502 Bad Gateway ErrGatewayTimeout = NewHTTPError(helper(http.StatusGatewayTimeout)) // HTTP 504 Gateway Timeout ErrHTTPVersionNotSupported = NewHTTPError(helper(http.StatusHTTPVersionNotSupported)) // HTTP 505 HTTP Version Not Supported ErrVariantAlsoNegotiates = NewHTTPError(helper(http.StatusVariantAlsoNegotiates)) // HTTP 506 Variant Also Negotiates ErrInsufficientStorage = NewHTTPError(helper(http.StatusInsufficientStorage)) // HTTP 507 Insufficient Storage ErrLoopDetected = NewHTTPError(helper(http.StatusLoopDetected)) // HTTP 508 Loop Detected ErrNotExtended = NewHTTPError(helper(http.StatusNotExtended)) // HTTP 510 Not Extended ErrNetworkAuthenticationRequired = NewHTTPError(helper(http.StatusNetworkAuthenticationRequired)) // HTTP 511 Network Authentication Required ErrValidatorNotRegistered = errors.New("validator not registered") ErrRendererNotRegistered = errors.New("renderer not registered") ErrInvalidRedirectCode = errors.New("invalid redirect status code") ErrCookieNotFound = errors.New("cookie not found") ErrInvalidCertOrKeyType = errors.New("invalid cert or key type, must be string or []byte") ErrInvalidListenerNetwork = errors.New("invalid listener network") )
Predefined HTTP errors
Functions ¶
func Bind ¶ added in v1.1.0
Bind implements the `Binder#Bind` function. Binding is done in following order: 1) path params; 2) query params; 3) request body. Each step COULD override previous step binded values. For single source binding use their own methods BindBody, BindQueryParams, BindPathParams.
func BindBody ¶ added in v1.1.0
BindBody binds request body contents to bindable object NB: then binding forms take note that this implementation uses standard library form parsing which parses form data from BOTH URL and BODY if content type is not MIMEMultipartForm See non-MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseForm See MIMEMultipartForm: https://golang.org/pkg/net/http/#Request.ParseMultipartForm
func BindHeaders ¶ added in v1.1.0
BindHeaders binds HTTP headers to a bindable object
func BindPathParams ¶ added in v1.1.0
BindPathParams binds path params to bindable object
func BindQueryParams ¶ added in v1.1.0
BindQueryParams binds query params to bindable object
func DefaultErrHandlerFunc ¶
func DefaultErrHandlerFunc(err error, w http.ResponseWriter)
DefaultErrHandlerFunc is the default centralized error handling function. It only triggers an error response for *HTTPError.
Types ¶
type ErrHandlerFunc ¶
type ErrHandlerFunc func(err error, w http.ResponseWriter)
ErrHandlerFunc defines the function signature for centralized error handling.
type HTTPError ¶
type HTTPError struct { StatusCode int // HTTP status code Msg string // Error message Internal error // Internal error }
HTTPError represents a custom error type inspired by Echo.
func NewHTTPError ¶
NewHTTPError creates a new HTTPError with the given status code and message.
func (*HTTPError) SetInternal ¶ added in v1.1.0
SetInternal sets the internal error for the HTTPError.
type HandlerFunc ¶
type HandlerFunc func(w http.ResponseWriter, r *http.Request) error
HandlerFunc defines the function signature for a handler. It returns an error, which is used for centralized error handling.
func Adator ¶
func Adator(fn func(w http.ResponseWriter, r *http.Request)) HandlerFunc
Adator converts a standard http.HandlerFunc to a HandlerFunc that returns an error.
type HelperResponseWriter ¶
type HelperResponseWriter struct {
http.ResponseWriter
}
HelperResponseWriter is a built-in type used to record the StatusCode and quickly send responses.
func NewHelperRW ¶
func NewHelperRW(w http.ResponseWriter) *HelperResponseWriter
NewHelperRW creates a new instance of HelperResponseWriter.
func (*HelperResponseWriter) Flush ¶
func (rw *HelperResponseWriter) Flush()
Flush implements the http.Flusher interface.
func (*HelperResponseWriter) HTML ¶
func (rw *HelperResponseWriter) HTML(statusCode int, html string) error
HTML sends an HTML response with the specified status code and HTML content.
func (*HelperResponseWriter) Hijack ¶
func (rw *HelperResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)
Hijack implements the http.Hijacker interface.
func (*HelperResponseWriter) JSON ¶
func (rw *HelperResponseWriter) JSON(statusCode int, data any) error
JSON sends a JSON response with the specified status code and data.
func (*HelperResponseWriter) Push ¶
func (rw *HelperResponseWriter) Push(target string, opts *http.PushOptions) error
Push implements the http.Pusher interface.
func (*HelperResponseWriter) String ¶
func (rw *HelperResponseWriter) String(statusCode int, s string) error
String sends a plain text response with the specified status code and string.
func (*HelperResponseWriter) Unwrap ¶
func (rw *HelperResponseWriter) Unwrap() http.ResponseWriter
Unwrap returns the wrapped ResponseWriter.
type MiddlewareFunc ¶
MiddlewareFunc defines the function signature for middleware. It wraps an http.Handler and returns a new http.Handler.
type RouteMiddlewareFunc ¶
type RouteMiddlewareFunc func(next HandlerFunc) HandlerFunc
RouteMiddlewareFunc defines the function signature for route-specific middleware. It wraps a HandlerFunc and returns a new HandlerFunc.
type ServeMux ¶
type ServeMux struct { http.ServeMux ErrHandlerFunc ErrHandlerFunc // Function for centralized error handling // contains filtered or unexported fields }
ServeMux embeds http.ServeMux and provides additional features like error handling and middleware.
func NewServeMux ¶
func NewServeMux() *ServeMux
NewServeMux returns a new instance of ServeMux with default settings.
func (*ServeMux) Connect ¶
func (sm *ServeMux) Connect(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Connect registers a new CONNECT route with optional route-specific middleware.
func (*ServeMux) Delete ¶
func (sm *ServeMux) Delete(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Delete registers a new DELETE route with optional route-specific middleware.
func (*ServeMux) Get ¶
func (sm *ServeMux) Get(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Get registers a new GET route with optional route-specific middleware.
func (*ServeMux) Group ¶
Group creates a new ServeMux for a specific URL prefix, allowing for route grouping.
func (*ServeMux) HandleFunc ¶
func (sm *ServeMux) HandleFunc(pattern string, h HandlerFunc)
HandleFunc registers a new route with a pattern and a handler function. The handler function can return an error for centralized error handling.
func (*ServeMux) Head ¶
func (sm *ServeMux) Head(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Head registers a new HEAD route with optional route-specific middleware.
func (*ServeMux) Options ¶
func (sm *ServeMux) Options(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Options registers a new OPTIONS route with optional route-specific middleware.
func (*ServeMux) Patch ¶
func (sm *ServeMux) Patch(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Patch registers a new PATCH route with optional route-specific middleware.
func (*ServeMux) Post ¶
func (sm *ServeMux) Post(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Post registers a new POST route with optional route-specific middleware.
func (*ServeMux) Put ¶
func (sm *ServeMux) Put(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Put registers a new PUT route with optional route-specific middleware.
func (*ServeMux) ServeHTTP ¶
func (sm *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP processes HTTP requests using the registered handlers and middleware.
func (*ServeMux) Trace ¶
func (sm *ServeMux) Trace(path string, h HandlerFunc, m ...RouteMiddlewareFunc)
Trace registers a new TRACE route with optional route-specific middleware.
func (*ServeMux) Use ¶
func (sm *ServeMux) Use(m ...MiddlewareFunc)
Use adds middleware to the ServeMux, which will be applied to all routes.