Documentation
¶
Index ¶
- Constants
- Variables
- func BindMod(c Ctx, out any) error
- func BindModValidate(c Ctx, out any) error
- func BindValidate(c Ctx, out any) error
- func DefaultErrorHandler(c Ctx, err error) error
- func GetErrorStatusCode(err error) int
- func GetTransformer() *mold.Transformer
- func GetValidator() *validator.Validate
- func Local[T any](c Ctx, name string) T
- func Mod(ctx context.Context, v any) error
- func ModValidate(ctx context.Context, v any) error
- func Parse[T any](c Ctx) (T, error)
- func ParseMod[T any](c Ctx) (T, error)
- func ParseModValidate[T any](c Ctx) (T, error)
- func ParseValidate[T any](c Ctx) (T, error)
- func Query[T any](c Ctx, name string, def ...T) T
- func UnsafeBytes(s string) []byte
- func UnsafeString(b []byte) string
- func Validate(v any) error
- type App
- func (a *App) Delete(path string, handlers ...Handler)
- func (a *App) Get(path string, handlers ...Handler)
- func (a *App) Group(path string, handlers ...Handler) Router
- func (a *App) Listen(addr string) error
- func (a *App) Patch(path string, handlers ...Handler)
- func (a *App) Post(path string, handlers ...Handler)
- func (a *App) Put(path string, handlers ...Handler)
- func (a *App) Shutdown() error
- func (a *App) Use(handlers ...Handler)
- type Bind
- type Config
- type Ctx
- type DeleteCookieParams
- type Error
- type ErrorHandler
- type FieldValidationError
- type Group
- func (g *Group) Delete(path string, handlers ...Handler)
- func (g *Group) Get(path string, handlers ...Handler)
- func (g *Group) Group(path string, handlers ...Handler) Router
- func (g *Group) Patch(path string, handlers ...Handler)
- func (g *Group) Post(path string, handlers ...Handler)
- func (g *Group) Put(path string, handlers ...Handler)
- func (g *Group) Use(handlers ...Handler)
- type Handler
- type JsonErrorHandlerConfig
- type Logger
- type Map
- type Redirect
- type Renderer
- type Route
- type RoutePath
- type Router
- type SetCookieParams
- type SilentLogger
- type TrustProxyConfig
Constants ¶
const ( SchemeHttp = "http" SchemeHttps = "https" )
Schemes
const ( MethodGet = "GET" MethodHead = "HEAD" MethodPost = "POST" MethodPut = "PUT" MethodPatch = "PATCH" // RFC 5789 MethodDelete = "DELETE" MethodConnect = "CONNECT" MethodOptions = "OPTIONS" MethodTrace = "TRACE" )
HTTP method names copied from net/http
const ( StatusContinue = 100 // RFC 9110, 15.2.1 StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusEarlyHints = 103 // RFC 8297 StatusOK = 200 // RFC 9110, 15.3.1 StatusCreated = 201 // RFC 9110, 15.3.2 StatusAccepted = 202 // RFC 9110, 15.3.3 StatusNonAuthoritativeInfo = 203 // RFC 9110, 15.3.4 StatusNoContent = 204 // RFC 9110, 15.3.5 StatusResetContent = 205 // RFC 9110, 15.3.6 StatusPartialContent = 206 // RFC 9110, 15.3.7 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 9110, 15.4.1 StatusMovedPermanently = 301 // RFC 9110, 15.4.2 StatusFound = 302 // RFC 9110, 15.4.3 StatusSeeOther = 303 // RFC 9110, 15.4.4 StatusNotModified = 304 // RFC 9110, 15.4.5 StatusUseProxy = 305 // RFC 9110, 15.4.6 StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8 StatusPermanentRedirect = 308 // RFC 9110, 15.4.9 StatusBadRequest = 400 // RFC 9110, 15.5.1 StatusPaymentRequired = 402 // RFC 9110, 15.5.3 StatusForbidden = 403 // RFC 9110, 15.5.4 StatusNotFound = 404 // RFC 9110, 15.5.5 StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6 StatusNotAcceptable = 406 // RFC 9110, 15.5.7 StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8 StatusRequestTimeout = 408 // RFC 9110, 15.5.9 StatusConflict = 409 // RFC 9110, 15.5.10 StatusGone = 410 // RFC 9110, 15.5.11 StatusLengthRequired = 411 // RFC 9110, 15.5.12 StatusPreconditionFailed = 412 // RFC 9110, 15.5.13 StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14 StatusRequestURITooLong = 414 // RFC 9110, 15.5.15 StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16 StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17 StatusExpectationFailed = 417 // RFC 9110, 15.5.18 StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused) StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20 StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusTooEarly = 425 // RFC 8470, 5.2. StatusUpgradeRequired = 426 // RFC 9110, 15.5.22 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 9110, 15.6.1 StatusNotImplemented = 501 // RFC 9110, 15.6.2 StatusBadGateway = 502 // RFC 9110, 15.6.3 StatusGatewayTimeout = 504 // RFC 9110, 15.6.5 StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.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 copied from net/http
const ( ContentTypeTextPlain = "text/plain" ContentTypeTextPlainUTF8 = "text/plain; charset=utf-8" ContentTypeTextHtml = "text/html" ContentTypeTextHtmlUTF8 = "text/html; charset=utf-8" ContentTypeTextXml = "text/xml" ContentTypeTextXmlUTF8 = "text/xml; charset=utf-8" ContentTypeForm = "application/x-www-form-urlencoded" ContentTypeFormUTF8 = "application/x-www-form-urlencoded; charset=utf-8" ContentTypeApplicationXml = "application/xml" ContentTypeApplicationXmlUTF8 = "application/xml; charset=utf-8" ContentTypeApplicationJson = "application/json" ContentTypeApplicationJsonUTF8 = "application/json; charset=utf-8" ContentTypeOctetStream = "application/octet-stream" )
MIME types for the Content-Type header
Variables ¶
var ( ErrBadRequest = NewError(StatusBadRequest, "bad request") ErrPaymentRequired = NewError(StatusPaymentRequired, "payment required") ErrForbidden = NewError(StatusForbidden, "forbidden") ErrNotFound = NewError(StatusNotFound, "not found") ErrMethodNotAllowed = NewError(StatusMethodNotAllowed, "method not allowed") ErrNotAcceptable = NewError(StatusNotAcceptable, "not acceptable") ErrTooManyRequests = NewError(StatusTooManyRequests, "too many requests") ErrUnsupportedMediaType = NewError(StatusUnsupportedMediaType, "unsupported media type") )
Functions ¶
func BindMod ¶
Binds the body of the request into an existing out value and runs any "mod" transformations on it. This does NOT run any validations on it; see BindModValidate[T] for that.
func BindModValidate ¶
Binds the body of the request into an existing out value, runs any "mod" transformations on it followed by "validate" validators.
func BindValidate ¶
Binds the body of the request into an existing out value and runs any "validate" validators on it. This does NOT run any transformations on it; see BindModValidate[T] for that.
func DefaultErrorHandler ¶
The default error handler, providing plaintext error output
func GetErrorStatusCode ¶
Gets the presumed status code for the given error
func GetTransformer ¶
func GetTransformer() *mold.Transformer
func GetValidator ¶
func Mod ¶
Runs any "mod" transformations on the given struct. To combine this with body parsing, see ParseMod[T].
func ModValidate ¶
Runs any "mod" transformations on the given struct, followed by any "validate" validators. To combine this with body parsing as well, see ParseModValidate[T] or BindModValidate[T].
func Parse ¶
Parses the body of the request into an instance of T. Does not perform any transformations or validations. See also ParseValidate[T] and ParseModValidate[T].
func ParseMod ¶
Parses the body of the request into an instance of T and runs any "mod" transformations on it. This does NOT run any validations on it; see ParseModValidate[T] for that.
func ParseModValidate ¶
Parses the body of the request into an instance of T, runs any "mod" transformations on it followed by "validate" validators.
func ParseValidate ¶
Parses the body of the request into an instance of T and runs any "validate" validators on it. This does NOT run any transformations on it; see ParseModValidate[T] for that.
func UnsafeBytes ¶
UnsafeBytes returns a byte pointer without allocation
func UnsafeString ¶
UnsafeString returns a string pointer without allocation
Types ¶
type Config ¶
type Config struct {
// Handler to use when errors occur. Defaults to fire.DefaultErrorHandler.
ErrorHandler ErrorHandler
// What header to use for the list of forwarded IPs. Defaults to "X-Forwarded-For".
ProxyHeaderForwardedFor string
// Whether to trust proxy headers, see also TrustProxyConfig. Defaults to false.
TrustProxy bool
// Configuration for trusted proxies.
TrustProxyConfig TrustProxyConfig
// Which logger to use for any internal log purposes. Defaults to fire.Logger.
Logger fasthttp.Logger
// Optional logger specifically for fasthttp messages. Defaults to fire.SilentLogger.
FastHttpLogger fasthttp.Logger
// Renderer to use for Ctx.Render*. Defaults to nil.
Renderer Renderer
}
type Ctx ¶
type Ctx interface {
App() *App
Request() *fasthttp.Request
Context() *fasthttp.RequestCtx
Scheme() string
Hostname() string
Method() string
Path() string
BaseURL() string
Bind() *Bind
Param(name string, def ...string) string
ParamInt(name string, def ...int) int
ParamUint(name string, def ...uint) uint
Queries() map[string]string
Query(name string, def ...string) string
QueryInt(name string, def ...int) int
QueryUint(name string, def ...uint) uint
PostArgs() map[string]string
PostArg(name string, def ...string) string
PostArgInt(name string, def ...int) int
PostArgUint(name string, def ...uint) uint
IP() string
IPs() []string
UserAgent() string
Header(name string) string
SetHeader(name, setValue string)
Cookie(name string) string
SetCookie(name, setValue string, params ...SetCookieParams)
DeleteCookie(name string, params ...DeleteCookieParams)
MediaType() string
ContentType() string
SetContentType(setValue string)
Next() error
Drop() error
Local(name string) any
SetLocal(name string, setValue any)
Redirect() Redirect
WithStatus(code int) Ctx
SendStatus(code int) error
Render(view string, data ...any) error
RenderLayout(layout, view string, data ...any) error
RenderPartial(view string, data ...any) (string, error)
Send(bytes []byte) error
SendString(str string) error
SendStream(stream io.Reader, size ...int) error
JSON(obj any) error
Write(p []byte) (n int, err error)
}
type DeleteCookieParams ¶
type ErrorHandler ¶
func MakeJsonErrorHandler ¶
func MakeJsonErrorHandler(config ...JsonErrorHandlerConfig) ErrorHandler
Make a default json error handler with the given configuration
func MakeRenderErrorHandler ¶
func MakeRenderErrorHandler(view string) ErrorHandler
Make a default rendering error handler with the given view
type FieldValidationError ¶
type FieldValidationError struct {
Field string `json:"field"`
Tag string `json:"tag"`
Param string `json:"param,omitempty"`
}
Field validation error used by the json error handler - see MakeJsonErrorHandler() and JsonErrorHandlerConfig
type JsonErrorHandlerConfig ¶
type JsonErrorHandlerConfig struct {
// Whether to include detailed field validation errors. Defaults to false.
ValidationErrors bool
// The field name for validation errors. Only used if ValidationErrors is true.
// Defaults to "validation_errors".
ValidationErrorsField string
// Whether to include the "param" field from validation errors. Defaults to false.
ValidationErrorsParam bool
}
Configuration that can be passed to MakeJsonErrorHandler()
type Redirect ¶
type Redirect interface {
// Redirect with status 307.
Temporary() Redirect
// Redirect with status 308.
Permanent() Redirect
// Redirect with status 301.
MovedPermanently() Redirect
// Redirect with status 302.
Found() Redirect
// Redirect with status 303. This is the default.
SeeOther() Redirect
// Perform the redirect.
To(to string) error
// Redirects to the referer or the fallback if set.
Back(fallback string) error
}
type Route ¶
type Route struct {
Path RoutePath `json:"path"`
Method string `json:"method"`
// contains filtered or unexported fields
}
func (*Route) CheckRouteParams ¶
func (*Route) RunHandlers ¶
type RoutePath ¶
type RoutePath struct {
// contains filtered or unexported fields
}
func ParseRoutePath ¶
func (RoutePath) IndexOfParam ¶
type Router ¶
type Router interface {
Use(handlers ...Handler)
Group(path string, handlers ...Handler) Router
Get(path string, handlers ...Handler)
Post(path string, handlers ...Handler)
Put(path string, handlers ...Handler)
Delete(path string, handlers ...Handler)
Patch(path string, handlers ...Handler)
// contains filtered or unexported methods
}
type SetCookieParams ¶
type SetCookieParams struct {
// Defines the host to which the cookie will be sent. Only the current domain
// can be set as the value, or a domain of a higher order, unless it is a
// public suffix. Setting the domain will make the cookie available to it, as
// well as to all its subdomains.
Domain string
// Indicates the path that must exist in the requested URL for the browser to
// send the Cookie header. Defaults to "/".
Path string
// Controls whether or not a cookie is sent with cross-site requests: that is,
// requests originating from a different site, including the scheme, from the
// site that set the cookie. This provides some protection against certain
// cross-site attacks, including cross-site request forgery (CSRF) attacks.
//
// For more information, see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie#samesitesamesite-value
SameSite fasthttp.CookieSameSite
// Indicates the maximum lifetime of the cookie as an HTTP-date timestamp. If
// unspecified, the cookie becomes a session cookie. A session finishes when
// the client shuts down, after which the session cookie is removed.
ExpireTime time.Time
// Indicates the number of seconds until the cookie expires. A zero or
// negative number will expire the cookie immediately. If both Expiretime and
// MaxAge are set, MaxAge has precedence.
MaxAge int
// Forbids JavaScript from accessing the cookie, for example, through the
// Document.cookie property.
HTTPOnly bool
// Indicates that the cookie is sent to the server only when a request is made
// with the https: scheme (except on localhost), and therefore, is more
// resistant to man-in-the-middle attacks.
Secure bool
// Indicates that the cookie should be stored using partitioned storage. Note
// that if this is set, the Secure directive must also be set.
Partitioned bool
}
Parameters to be passed to Ctx.SetCookie.
Some documentation below taken from MDN for convenience from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie by Mozilla Contributors, licensed under CC-BY-SA 2.5
type SilentLogger ¶
type SilentLogger struct{}
func (*SilentLogger) Printf ¶
func (l *SilentLogger) Printf(format string, args ...any)
type TrustProxyConfig ¶
type TrustProxyConfig struct {
// List of IP specific ranges/addresses to trust. Defaults to an empty list.
Proxies []string
// Whether to trust the private IP ranges 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and fd00::/8. Defaults to false.
Private bool
// Whether to trust localhost IP range 127.0.0.0/8 and ::1. Defaults to false.
Loopback bool
// Whether to trust link-local IP ranges 169.254.0.0/16 and fe80::/10. Defaults to false.
LinkLocal bool
// contains filtered or unexported fields
}
func (*TrustProxyConfig) ParseProxies ¶
func (tpc *TrustProxyConfig) ParseProxies() error
Parses the public Proxies into the private cached pre-parsed fields.