Documentation
¶
Overview ¶
Package fasthttpbind is the fasthttp half of the binding runtime. It declares the same names as the net/http runtime over *fasthttp.RequestCtx, so generated code imports it under the httpbind alias and its call selectors read the same on either transport:
import httpbind "github.com/shibukawa/tinybind-go/fasthttpbind"
Nothing here is written by hand in an application. Generation emits every call, which is why the declarations reuse the net/http names instead of taking a prefix that would only matter to a human reader.
Pooled memory ¶
A RequestCtx and every byte slice reachable from it are pooled and reused once the handler returns. Every value this package hands back is copied out, including the JSON document a binder parses. Nothing returned by Bind may alias the request.
Error bytes ¶
WriteError derives its document through the same shared code the net/http runtime uses, so the two transports emit identical problem bodies for identical errors.
Index ¶
- Constants
- func AcceptsCBOR(ctx *fasthttp.RequestCtx) bool
- func ActionSelector(ctx *fasthttp.RequestCtx, field string) string
- func AppendFileJSON(dst []byte, f File) []byte
- func BadRequest(problem Problem, cause ...error) error
- func Bind[T any](ctx *fasthttp.RequestCtx) (T, error)
- func BindError(field, location, message string) error
- func CheckDate(s string) bool
- func CheckDateTime(s string) bool
- func CheckEmail(s string) bool
- func CheckTime(s string) bool
- func CheckUUID(s string) bool
- func Conflict(problem Problem, cause ...error) error
- func CookieValue(ctx *fasthttp.RequestCtx, name string) (string, bool)
- func DispatchAction(ctx *fasthttp.RequestCtx, handler func(*fasthttp.RequestCtx))
- func Forbidden(problem Problem, cause ...error) error
- func HeaderValue(ctx *fasthttp.RequestCtx, key string) string
- func Internal(err error) error
- func IsCBORRequest(ctx *fasthttp.RequestCtx) bool
- func IsJSONRequest(ctx *fasthttp.RequestCtx) bool
- func JSONBodyError(err error) error
- func JSONBodyNotObject() error
- func MaxCBORBodyBytes() int64
- func MaxJSONBodyBytes() int64
- func MaxMultipartBodyBytes() int64
- func NotFound(problem Problem, cause ...error) error
- func ParseBool(s string) (bool, error)
- func ParseBytes(s string) ([]byte, error)
- func ParseFloat64(s string) (float64, error)
- func ParseFormMap(ctx *fasthttp.RequestCtx) (map[string]string, error)
- func ParseInt(s string) (int, error)
- func ParseInt64(s string) (int64, error)
- func ParseIntBits(s string, bits int) (int64, error)
- func ParseMultipartMap(ctx *fasthttp.RequestCtx) (form map[string]string, files map[string]File, err error)
- func ParseUintBits(s string, bits int) (uint64, error)
- func PathValue(ctx *fasthttp.RequestCtx, key string) string
- func PayloadTooLarge(problem Problem, cause ...error) error
- func Queries(ctx *fasthttp.RequestCtx) *fasthttp.Args
- func QueryLookup(q *fasthttp.Args, key string) (string, bool)
- func QueryLookupAll(q *fasthttp.Args, key string) []string
- func QueryValue(ctx *fasthttp.RequestCtx, key string) (string, bool)
- func ReadCBORBody(ctx *fasthttp.RequestCtx) ([]byte, error)
- func ReadFormBody(ctx *fasthttp.RequestCtx, wantForm, wantFiles bool) (map[string]string, map[string]File, error)
- func ReadJSONBody(ctx *fasthttp.RequestCtx) ([]byte, error)
- func ReadJSONBodyOwned(ctx *fasthttp.RequestCtx) ([]byte, error)
- func RegisterBind[T any](fn func(*fasthttp.RequestCtx) (T, error))
- func RegisterWrite[T any](fn func(*fasthttp.RequestCtx, T) error)
- func RestFormAny(formBody map[string]string, exclude []string) map[string]any
- func RestFormRaw(formBody map[string]string, exclude []string) map[string]json.RawMessage
- func SetMaxCBORBodyBytes(n int64)
- func SetMaxJSONBodyBytes(n int64)
- func SetMaxMultipartBodyBytes(n int64)
- func SetSocketDefaults(opts SocketOptions)
- func SetStreamErrorHandler(fn func(error))
- func Unauthorized(problem Problem, cause ...error) error
- func Validation(fields ...FieldError) error
- func VaryAccept(ctx *fasthttp.RequestCtx)
- func WebSocket[In, Out any](ctx *fasthttp.RequestCtx, fn func(*Socket[In, Out]) error) error
- func WebSocketWith[In, Out any](ctx *fasthttp.RequestCtx, opts SocketOptions, fn func(*Socket[In, Out]) error) error
- func Write[T any](ctx *fasthttp.RequestCtx, value T) error
- func WriteCBORBytes(ctx *fasthttp.RequestCtx, status int, data []byte) error
- func WriteError(ctx *fasthttp.RequestCtx, err error)
- func WriteJSONBytes(ctx *fasthttp.RequestCtx, status int, data []byte) error
- func WriteStatus[T any](ctx *fasthttp.RequestCtx, status int, value T) error
- func WriteStream[T any](ctx *fasthttp.RequestCtx, fn func(*Stream[T]) error)
- type FieldError
- type File
- type HTTPError
- type Problem
- type Socket
- type SocketOptions
- type Stream
- type StreamFormat
Constants ¶
const ( // StreamSSE is text/event-stream (data: <json>\n\n). StreamSSE = bindcore.StreamSSE // StreamNDJSON is application/x-ndjson (one JSON object per line). StreamNDJSON = bindcore.StreamNDJSON // StreamJSONArray is application/json as one JSON array document. StreamJSONArray = bindcore.StreamJSONArray )
const DefaultActionSelectorField = "_action"
DefaultActionSelectorField is the hidden field a generated form carries to say which server function a native submit is for. It matches the net/http half, so one generated form works on either backend.
const DefaultMaxCBORBodyBytes = bindcore.DefaultMaxCBORBodyBytes
DefaultMaxCBORBodyBytes is the default cap for CBOR body reads (1 MiB).
const DefaultMaxJSONBodyBytes = jsonbind.DefaultMaxJSONBodyBytes
DefaultMaxJSONBodyBytes is the default cap for JSON document reads (1 MiB).
const DefaultMaxMultipartBodyBytes = bindcore.DefaultMaxMultipartBodyBytes
DefaultMaxMultipartBodyBytes is the default cap on multipart request bodies.
Variables ¶
This section is empty.
Functions ¶
func AcceptsCBOR ¶ added in v0.5.19
func AcceptsCBOR(ctx *fasthttp.RequestCtx) bool
AcceptsCBOR reports whether the client asked for a CBOR response. Only an explicit application/cbor entry in Accept counts; wildcards keep the JSON default.
func ActionSelector ¶ added in v0.5.8
func ActionSelector(ctx *fasthttp.RequestCtx, field string) string
ActionSelector returns the server function selector a native form submit carried, or the empty string when it carried none.
The query is read before the body for the reason the net/http half gives: a submit button's formaction carries the selector when one form dispatches to several handlers, and that channel has to win rather than merely coexist.
func AppendFileJSON ¶
AppendFileJSON appends an uploaded file the way encoding/json rendered it before generated encoders stopped going through reflection.
func BadRequest ¶
BadRequest returns a 400 Bad Request error.
func Bind ¶
func Bind[T any](ctx *fasthttp.RequestCtx) (T, error)
Bind maps a fasthttp request into a typed request value. Dispatch uses a registry of generated binders; field mapping does not use reflect.
Every field the binder fills is copied out of the pooled request, so the returned value stays valid after the handler returns.
func CheckDateTime ¶
CheckDateTime reports whether s is RFC3339 (fractional seconds accepted).
func CheckEmail ¶
CheckEmail reports whether s is a pragmatic (non-RFC5322) email.
func CookieValue ¶
func CookieValue(ctx *fasthttp.RequestCtx, name string) (string, bool)
CookieValue returns a cookie value if present.
func DispatchAction ¶ added in v0.5.8
func DispatchAction(ctx *fasthttp.RequestCtx, handler func(*fasthttp.RequestCtx))
DispatchAction runs one server function on the page's own POST route and applies the post-redirect-get default, matching the net/http half.
A handler that writes nothing gets a 303 back to the page it was submitted from; one that writes a status, a header, or a body keeps that response.
The observation is made by comparing the response before and after rather than by wrapping the writer, because fasthttp carries the request and the response in one value and there is nothing to wrap.
func HeaderValue ¶
func HeaderValue(ctx *fasthttp.RequestCtx, key string) string
HeaderValue returns a request header.
func IsCBORRequest ¶ added in v0.5.19
func IsCBORRequest(ctx *fasthttp.RequestCtx) bool
IsCBORRequest reports whether the request body should be treated as CBOR. Matches application/cbor and *+cbor types (RFC 6839).
func IsJSONRequest ¶
func IsJSONRequest(ctx *fasthttp.RequestCtx) bool
IsJSONRequest reports whether the request body should be treated as JSON.
func JSONBodyError ¶ added in v0.5.21
JSONBodyError wraps a structural JSON failure from a binder's inline body walk as a 400 problem.
func JSONBodyNotObject ¶ added in v0.5.21
func JSONBodyNotObject() error
JSONBodyNotObject is the 400 for a body that decodes to a non-object.
func MaxCBORBodyBytes ¶ added in v0.5.19
func MaxCBORBodyBytes() int64
MaxCBORBodyBytes returns the effective CBOR body limit.
func MaxJSONBodyBytes ¶
func MaxJSONBodyBytes() int64
MaxJSONBodyBytes returns the effective JSON body limit.
func MaxMultipartBodyBytes ¶
func MaxMultipartBodyBytes() int64
MaxMultipartBodyBytes returns the effective global multipart body limit.
func ParseBytes ¶ added in v0.5.24
ParseBytes decodes a base64 query, path, header or cookie value into a byte field. Both alphabets are accepted, padded or not, since a value that travelled through a URL may have been written either way; the encoder always produces padded standard base64.
func ParseFloat64 ¶
ParseFloat64 converts a string to float64.
func ParseFormMap ¶
func ParseFormMap(ctx *fasthttp.RequestCtx) (map[string]string, error)
ParseFormMap parses an urlencoded form body into a flat map (first value wins).
func ParseIntBits ¶ added in v0.5.23
ParseIntBits converts a string to a signed integer of the given width, reporting a value the width cannot hold rather than truncating it. bits is 0 for platform-width int.
The generated binder calls this for every signed width beside int and int64, which keep the two helpers they already had so their output does not move.
func ParseMultipartMap ¶
func ParseMultipartMap(ctx *fasthttp.RequestCtx) (form map[string]string, files map[string]File, err error)
ParseMultipartMap parses a multipart/form-data body into scalar form fields (first value wins) and named file parts (first file wins per field name).
The body is capped at MaxMultipartBodyBytes(). fasthttp has already read the body by the time a handler runs, so this bound is a policy check rather than the memory guarantee; the memory guarantee belongs to the server's own per-request limit.
func ParseUintBits ¶ added in v0.5.23
ParseUintBits is the unsigned twin of ParseIntBits. A leading minus is an error, so a negative query value cannot arrive as a large positive one.
func PathValue ¶
func PathValue(ctx *fasthttp.RequestCtx, key string) string
PathValue returns the path value for key.
fasthttp has no routing of its own, so the value comes from whatever the router stored as a user value rather than from the transport.
func PayloadTooLarge ¶
PayloadTooLarge returns a 413 Payload Too Large error.
func Queries ¶
func Queries(ctx *fasthttp.RequestCtx) *fasthttp.Args
Queries returns the parsed query arguments. Generated binders call this once per request and resolve each field with QueryLookup.
func QueryLookup ¶
QueryLookup returns the first value for key from pre-parsed query values. A key present with an empty value reports ("", true), matching net/http.
Peek runs first because both it and Has are linear scans of the same list: a hit answers in one pass, and the second scan is paid only to tell a present-but-empty key apart from an absent one.
func QueryLookupAll ¶ added in v0.5.26
QueryLookupAll returns every value for key, in the order the URL wrote them, which is the array spelling an urlencoded form submits for a repeated control name. An empty value contributes nothing, matching the net/http counterpart: a blank control submits its key with no value, and counting one would invent an element no user chose.
func QueryValue ¶
func QueryValue(ctx *fasthttp.RequestCtx, key string) (string, bool)
QueryValue returns the first query parameter value for key.
func ReadCBORBody ¶ added in v0.5.19
func ReadCBORBody(ctx *fasthttp.RequestCtx) ([]byte, error)
ReadCBORBody hands back the request body, bounded by MaxCBORBodyBytes.
The bytes are copied out of the transport's pooled buffer: a generated decoder borrows sub-slices while it walks, and this runtime cannot see whether one of them (a captured raw member, say) outlives the request.
func ReadFormBody ¶ added in v0.5.21
func ReadFormBody(ctx *fasthttp.RequestCtx, wantForm, wantFiles bool) (map[string]string, map[string]File, error)
ReadFormBody dispatches on the form content types alone, for binders that read their JSON body inline through ReadJSONBody.
func ReadJSONBody ¶ added in v0.5.21
func ReadJSONBody(ctx *fasthttp.RequestCtx) ([]byte, error)
ReadJSONBody returns the raw JSON body under MaxJSONBodyBytes.
The bytes alias the pooled request. That is safe for the binders emitted against this name because their inline walk copies every value it keeps — each scalar leaf becomes a fresh string — so nothing aliases the pool once the bind returns. A binder that does hand raw spans onward is emitted against ReadJSONBodyOwned instead.
func ReadJSONBodyOwned ¶ added in v0.5.21
func ReadJSONBodyOwned(ctx *fasthttp.RequestCtx) ([]byte, error)
ReadJSONBodyOwned is ReadJSONBody with the bytes copied out of the pooled request, for a binder whose raw body spans outlive the bind — a json.RawMessage field or rest map, or a foreign decoder whose retention is its own business.
func RegisterBind ¶
func RegisterBind[T any](fn func(*fasthttp.RequestCtx) (T, error))
RegisterBind registers a generated binder for T. Call from generated init(); field mapping lives entirely inside fn.
func RegisterWrite ¶
func RegisterWrite[T any](fn func(*fasthttp.RequestCtx, T) error)
RegisterWrite registers a generated writer for T.
func RestFormAny ¶
RestFormAny builds map[string]any from leftover form keys not in exclude.
func RestFormRaw ¶
RestFormRaw builds map[string]json.RawMessage from leftover form keys.
func SetMaxCBORBodyBytes ¶ added in v0.5.19
func SetMaxCBORBodyBytes(n int64)
SetMaxCBORBodyBytes changes the process-wide CBOR body limit. A non-positive value restores DefaultMaxCBORBodyBytes. Both transport runtimes honour the same value.
func SetMaxJSONBodyBytes ¶
func SetMaxJSONBodyBytes(n int64)
SetMaxJSONBodyBytes changes the process-wide JSON body limit. A non-positive value restores DefaultMaxJSONBodyBytes.
func SetMaxMultipartBodyBytes ¶
func SetMaxMultipartBodyBytes(n int64)
SetMaxMultipartBodyBytes sets the global multipart body size limit. The value is shared with the net/http runtime, so configuring it once configures both.
func SetSocketDefaults ¶ added in v0.5.4
func SetSocketDefaults(opts SocketOptions)
SetSocketDefaults installs the process-wide socket options. It is shared with the net/http runtime, so installing them once covers both.
func SetStreamErrorHandler ¶
func SetStreamErrorHandler(fn func(error))
SetStreamErrorHandler installs the destination for stream failures raised after the response status has been sent. It is shared with the net/http runtime, so installing it once covers both.
func Unauthorized ¶
Unauthorized returns a 401 Unauthorized error.
func Validation ¶
func Validation(fields ...FieldError) error
Validation returns a 400 Bad Request validation error with field details.
func VaryAccept ¶ added in v0.5.20
func VaryAccept(ctx *fasthttp.RequestCtx)
VaryAccept records that the response body depends on the Accept header, so a shared cache keys the entry on it. Generated writers call it before negotiating; without it a cache could hand a CBOR body to a JSON client.
func WebSocket ¶ added in v0.5.4
WebSocket upgrades the request, runs fn against a typed socket, and closes the socket when fn returns.
The return value is the handshake error and nothing else. A non-nil value means the refusal response has already been written, as RFC 9457 Problem Details. fn's own error is raised after the 101 has gone out, so it reaches the handler installed with SetStreamErrorHandler instead.
fn runs after the handler has returned, from the hijacked connection, so it must not read ctx: everything it needs is captured before WebSocket returns. fasthttp closes the connection when fn returns, which is what the callback shape wants and why KeepHijackedConns stays off.
func WebSocketWith ¶ added in v0.5.4
func WebSocketWith[In, Out any](ctx *fasthttp.RequestCtx, opts SocketOptions, fn func(*Socket[In, Out]) error) error
WebSocketWith is WebSocket with per-call options.
func Write ¶
func Write[T any](ctx *fasthttp.RequestCtx, value T) error
Write serializes a typed response value via a registered writer. Status is always 200 OK; use WriteStatus for other success codes.
There is no separate request parameter: RequestCtx carries both halves, and the net/http signature only takes r to reach negotiation it then discards.
func WriteCBORBytes ¶ added in v0.5.19
func WriteCBORBytes(ctx *fasthttp.RequestCtx, status int, data []byte) error
WriteCBORBytes writes an already-encoded CBOR document, the WriteJSONBytes twin. Generated writers build the body into a pooled buffer and hand it over here.
func WriteError ¶
func WriteError(ctx *fasthttp.RequestCtx, err error)
WriteError writes err as an RFC 9457 Problem Details response. Internal causes are not exposed in the client body.
The document is derived by the same shared code the net/http runtime calls, so both transports emit identical bytes for identical errors.
func WriteJSONBytes ¶
func WriteJSONBytes(ctx *fasthttp.RequestCtx, status int, data []byte) error
WriteJSONBytes writes an already-encoded document. Generated writers build the body into a pooled buffer and hand it over here, so the response path never reflects over the value and never allocates an intermediate map.
func WriteStatus ¶
func WriteStatus[T any](ctx *fasthttp.RequestCtx, status int, value T) error
WriteStatus serializes value with an explicit HTTP status code using the registered encoder for T (no field-walking reflection on T). For status 204 No Content, the body is not written.
func WriteStream ¶
func WriteStream[T any](ctx *fasthttp.RequestCtx, fn func(*Stream[T]) error)
WriteStream opens a negotiated stream, runs fn against it, and closes it.
The headers and status go out while the handler still owns the context; fn itself runs from the body stream writer, after the handler has returned. That inversion is why the entry point returns nothing: an error raised in fn has no way back to handler code, on this transport or the other, so both route it to the handler installed with SetStreamErrorHandler.
Because fn outlives the handler, it must not read ctx. Everything the stream needs is captured before WriteStream returns.
Types ¶
type FieldError ¶
type FieldError = bindcore.FieldError
FieldError describes a single field-level validation failure.
func Field ¶
func Field(field, location, message string) FieldError
Field builds a field-level validation error.
type HTTPError ¶
HTTPError is an HTTP-mapped error with optional RFC 9457 details and cause.
func AsHTTPError ¶
AsHTTPError extracts *HTTPError from err if present.
type Socket ¶ added in v0.5.4
Socket is a typed WebSocket connection. It is the same type the net/http runtime uses, so a callback body compiles unchanged on either transport.
type SocketOptions ¶ added in v0.5.4
type SocketOptions = bindcore.SocketOptions
SocketOptions configures one socket. A zero field takes the process default installed with SetSocketDefaults.
func SocketDefaults ¶ added in v0.5.4
func SocketDefaults() SocketOptions
SocketDefaults returns the effective process defaults.
type Stream ¶
Stream is a typed incremental response stream. It is the same type the net/http runtime uses, so the events produce the same bytes here.
type StreamFormat ¶
type StreamFormat = bindcore.StreamFormat
StreamFormat is the negotiated on-the-wire format for Stream[T].
func NegotiateStreamFormat ¶
func NegotiateStreamFormat(ctx *fasthttp.RequestCtx) StreamFormat
NegotiateStreamFormat selects SSE, NDJSON, or JSON array using the ?stream= query value, then Accept, then User-Agent, defaulting to NDJSON.