fasthttpbind

package
v0.5.18 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 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 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 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 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 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 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 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 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 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 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