fasthttpbind

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 9, 2026 License: Apache-2.0 Imports: 8 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 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 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 BytesJSONMap

func BytesJSONMap(data []byte) (*jsonbind.Object, error)

BytesJSONMap splits a full JSON object document into its raw fields.

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 DecodeJSONBool

func DecodeJSONBool(raw json.RawMessage) (bool, error)

DecodeJSONBool unmarshals a JSON raw value as bool.

func DecodeJSONBoolSlice

func DecodeJSONBoolSlice(raw []byte) ([]bool, error)

DecodeJSONBoolSlice decodes a JSON array of bools.

func DecodeJSONFloat64

func DecodeJSONFloat64(raw json.RawMessage) (float64, error)

DecodeJSONFloat64 unmarshals a JSON raw value as float64.

func DecodeJSONFloat64Slice

func DecodeJSONFloat64Slice(raw []byte) ([]float64, error)

DecodeJSONFloat64Slice decodes a JSON array of float64.

func DecodeJSONInt

func DecodeJSONInt(raw json.RawMessage) (int, error)

DecodeJSONInt unmarshals a JSON raw value as int.

func DecodeJSONInt64

func DecodeJSONInt64(raw json.RawMessage) (int64, error)

DecodeJSONInt64 unmarshals a JSON raw value as int64.

func DecodeJSONInt64Slice

func DecodeJSONInt64Slice(raw []byte) ([]int64, error)

DecodeJSONInt64Slice decodes a JSON array of int64.

func DecodeJSONIntSlice

func DecodeJSONIntSlice(raw []byte) ([]int, error)

DecodeJSONIntSlice decodes a JSON array of ints.

func DecodeJSONMapStringString

func DecodeJSONMapStringString(raw []byte) (map[string]string, error)

DecodeJSONMapStringString decodes a JSON object with string values.

func DecodeJSONString

func DecodeJSONString(raw json.RawMessage) (string, error)

DecodeJSONString unmarshals a JSON raw value as string.

func DecodeJSONStringSlice

func DecodeJSONStringSlice(raw []byte) ([]string, error)

DecodeJSONStringSlice decodes a JSON array of strings.

func Forbidden

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

Forbidden returns a 403 Forbidden error.

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 IsFormRequest

func IsFormRequest(ctx *fasthttp.RequestCtx) bool

IsFormRequest reports application/x-www-form-urlencoded.

func IsJSONRequest

func IsJSONRequest(ctx *fasthttp.RequestCtx) bool

IsJSONRequest reports whether the request body should be treated as JSON.

func IsMultipartRequest

func IsMultipartRequest(ctx *fasthttp.RequestCtx) bool

IsMultipartRequest reports multipart/form-data.

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

func QueryLookup(q *fasthttp.Args, 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 QueryValue

func QueryValue(ctx *fasthttp.RequestCtx, key string) (string, bool)

QueryValue returns the first query parameter value for key.

func RawJSONArray

func RawJSONArray(raw []byte) ([][]byte, error)

RawJSONArray splits a JSON array into its raw element values.

func RawJSONMap

func RawJSONMap(raw []byte) (*jsonbind.Object, error)

RawJSONMap splits a JSON object value into its raw fields.

func ReadBody

func ReadBody(ctx *fasthttp.RequestCtx, wantForm, wantFiles bool) (*jsonbind.Object, map[string]string, map[string]File, error)

ReadBody dispatches on the request content type and reads the body at most once on behalf of a generated binder. wantForm/wantFiles mirror which body kinds the binder's fields can consume; a request whose content type matches none of them yields all-nil results without error.

func ReadJSONObject

func ReadJSONObject(ctx *fasthttp.RequestCtx) (*jsonbind.Object, error)

ReadJSONObject splits a JSON object body into its raw fields.

The returned Object holds subslices of the document, so the pooled body is copied first: a generated binder may hand those raw bytes straight into a json.RawMessage rest map, which would otherwise outlive the request.

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 map[string]string, exclude []string) map[string]any

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

func RestFormRaw

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

RestFormRaw builds map[string]json.RawMessage from leftover form keys.

func RestJSONAny

func RestJSONAny(jsonBody *jsonbind.Object, exclude []string) (map[string]any, error)

RestJSONAny builds map[string]any from leftover JSON object keys not in exclude.

func RestJSONNames

func RestJSONNames(jsonBody *jsonbind.Object, exclude []string) []string

RestJSONNames lists leftover JSON object keys not in exclude.

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

func WriteJSON(ctx *fasthttp.RequestCtx, status int, v any) error

WriteJSON is a helper for generated writers: encode a pre-built map/slice without reflecting over application structs.

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