fasthttpbind

package
v0.5.34 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 19, 2026 License: Apache-2.0 Imports: 9 Imported by: 1

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

View Source
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
)
View Source
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.

View Source
const DefaultMaxCBORBodyBytes = bindcore.DefaultMaxCBORBodyBytes

DefaultMaxCBORBodyBytes is the default cap for CBOR body reads (1 MiB).

View Source
const DefaultMaxJSONBodyBytes = jsonbind.DefaultMaxJSONBodyBytes

DefaultMaxJSONBodyBytes is the default cap for JSON document reads (1 MiB).

View Source
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

func AppendFileJSON(dst []byte, f File) []byte

AppendFileJSON appends an uploaded file the way encoding/json rendered it before generated encoders stopped going through reflection.

func BadRequest

func BadRequest(problem Problem, cause ...error) error

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 BindError

func BindError(field, location, message string) error

BindError is returned when binding fails for a specific field/source.

func CheckDate

func CheckDate(s string) bool

CheckDate reports whether s is an ISO date (YYYY-MM-DD / time.DateOnly).

func CheckDateTime

func CheckDateTime(s string) bool

CheckDateTime reports whether s is RFC3339 (fractional seconds accepted).

func CheckEmail

func CheckEmail(s string) bool

CheckEmail reports whether s is a pragmatic (non-RFC5322) email.

func CheckTime

func CheckTime(s string) bool

CheckTime reports whether s is an ISO time (HH:MM:SS / time.TimeOnly).

func CheckUUID

func CheckUUID(s string) bool

CheckUUID reports whether s is a UUID string (8-4-4-4-12 hex with dashes).

func Conflict

func Conflict(problem Problem, cause ...error) error

Conflict returns a 409 Conflict error.

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 Forbidden

func Forbidden(problem Problem, cause ...error) error

Forbidden returns a 403 Forbidden error.

func FormLookup added in v0.5.34

func FormLookup(f FormValues, key string) (string, bool)

FormLookup returns the first value for key in a form body.

func HeaderValue

func HeaderValue(ctx *fasthttp.RequestCtx, key string) string

HeaderValue returns a request header.

func Internal

func Internal(err error) error

Internal returns a 500 Internal Server Error that wraps err.

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 IsNormalClose added in v0.5.27

func IsNormalClose(err error) bool

IsNormalClose reports whether a socket error is the ordinary end of the connection rather than a failure. It answers the same as the net/http surface's, which is what lets one Read loop end quietly on either transport.

func JSONBodyError added in v0.5.21

func JSONBodyError(err error) error

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 NotFound

func NotFound(problem Problem, cause ...error) error

NotFound returns a 404 Not Found error.

func ParseBool

func ParseBool(s string) (bool, error)

ParseBool converts a string to bool.

func ParseBytes added in v0.5.24

func ParseBytes(s string) ([]byte, error)

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

func ParseFloat64(s string) (float64, error)

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 ParseInt

func ParseInt(s string) (int, error)

ParseInt converts a string to int.

func ParseInt64

func ParseInt64(s string) (int64, error)

ParseInt64 converts a string to int64.

func ParseIntBits added in v0.5.23

func ParseIntBits(s string, bits int) (int64, error)

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

func ParseUintBits(s string, bits int) (uint64, error)

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

func PayloadTooLarge(problem Problem, cause ...error) error

PayloadTooLarge returns a 413 Payload Too Large error.

func QueryLookup

func QueryLookup(q QueryValues, key string) (string, bool)

QueryLookup returns the first value for key from pre-parsed query values. A key present with an empty value reports ("", true), matching net/http.

func QueryLookupAll added in v0.5.26

func QueryLookupAll(q QueryValues, key string) []string

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.

It copies the query out of the pooled request on every call, so a caller resolving several fields calls Queries once and QueryLookup per field, which is what generated binders do.

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 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

func RestFormAny(formBody FormValues, exclude []string) map[string]any

RestFormAny builds map[string]any from leftover form keys not in exclude.

func RestFormRaw

func RestFormRaw(formBody FormValues, exclude []string) map[string]json.RawMessage

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

func Unauthorized(problem Problem, cause ...error) error

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

func WebSocket[In, Out any](ctx *fasthttp.RequestCtx, fn func(*Socket[In, Out]) error) error

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 to the response via a registered writer, or, for a type carrying its own encoder, through jsonbind.Appender. Status is always 200 OK; use WriteStatus for other success codes.

The interface arm mirrors the net/http half, for the reason its doc gives: a type carrying a method has an author-written encoder, and it is what lets a value from a package this build never analyzed be answered with at all. A handler returning such a type must not work on one transport and report missing_codec on the other.

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 File

type File = bindcore.File

File is an uploaded file bound from a multipart/form-data part.

type FormValues added in v0.5.34

type FormValues = bindcore.FormValues

FormValues is a form body read once; see bindcore.FormValues. Generated binders ask it for their fields through FormLookup.

func ReadFormBody added in v0.5.21

func ReadFormBody(ctx *fasthttp.RequestCtx, wantForm, wantFiles bool) (FormValues, map[string]File, error)

ReadFormBody dispatches on the form content types alone, for binders that read their JSON body inline through ReadJSONBody.

An urlencoded body is split by the one implementation the query string uses, over a copy of the pooled body taken once, so the two transports admit the same pairs; the driver's own PostArgs parse is not consulted.

type HTTPError

type HTTPError = bindcore.HTTPError

HTTPError is an HTTP-mapped error with optional RFC 9457 details and cause.

func AsHTTPError

func AsHTTPError(err error) (*HTTPError, bool)

AsHTTPError extracts *HTTPError from err if present.

type Problem

type Problem = bindcore.Problem

Problem is an application error payload carried by status helpers.

type QueryValues added in v0.5.27

type QueryValues = bindcore.QueryValues

QueryValues is the request's query string split once into raw key=value spans. It is an alias, like the error model and File, so a binder holds the same type on either transport and the lookups cannot drift apart.

func Queries

func Queries(ctx *fasthttp.RequestCtx) QueryValues

Queries parses the request's query string once. Generated binders call this once per request and resolve each field with QueryLookup.

It splits the raw query itself rather than reading ctx.QueryArgs(), because the driver's parser admits pairs url.ParseQuery drops — one carrying a semicolon, one whose percent escape is broken — and the two runtimes then bind different values for a query the client chose. bindcore.ParseQuery is the one implementation both surfaces answer from.

The pooled query bytes are converted once here, so every span the lookups cut from them is owned by this request and none can outlive it.

type Socket added in v0.5.4

type Socket[In, Out any] = bindcore.Socket[In, Out]

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

type Stream[T any] = bindcore.Stream[T]

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL