Documentation
¶
Overview ¶
Package httpbind provides generated, reflection-free net/http request and response binding. Standalone JSON and SQL mapping live in the jsonbind and sqlbind packages so consumers do not compile unrelated platform dependencies.
Index ¶
- Constants
- func AcceptsCBOR(r *http.Request) bool
- func ActionSelector(r *http.Request, field string) string
- func AppendFileJSON(dst []byte, f File) []byte
- func AssembleOpenAPI() (jsonDoc []byte, err error)
- func BadRequest(problem Problem, cause ...error) error
- func Bind[T any](r *http.Request) (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(r *http.Request, name string) (string, bool)
- func DispatchAction(w http.ResponseWriter, r *http.Request, handler http.HandlerFunc)
- func Forbidden(problem Problem, cause ...error) error
- func HeaderValue(r *http.Request, key string) string
- func Internal(err error) error
- func IsCBORRequest(r *http.Request) bool
- func IsJSONRequest(r *http.Request) 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 OpenAPIDocument() ([]byte, error)
- func OpenAPIJSON(w http.ResponseWriter, r *http.Request)
- func ParseBool(s string) (bool, error)
- func ParseBytes(s string) ([]byte, error)
- func ParseFloat64(s string) (float64, error)
- func ParseFormMap(r *http.Request) (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(r *http.Request) (form map[string]string, files map[string]File, err error)
- func ParseUintBits(s string, bits int) (uint64, error)
- func PathValue(r *http.Request, key string) string
- func PayloadTooLarge(problem Problem, cause ...error) error
- func QueryLookup(q QueryValues, key string) (string, bool)
- func QueryValue(r *http.Request, key string) (string, bool)
- func ReadActionBody(r *http.Request) ([]byte, error)
- func ReadCBORBody(r *http.Request) ([]byte, error)
- func ReadFormBody(r *http.Request, wantForm, wantFiles bool) (map[string]string, map[string]File, error)
- func ReadJSONBody(r *http.Request) ([]byte, error)
- func ReadJSONBodyOwned(r *http.Request) ([]byte, error)
- func Redirect(target string, status ...int) error
- func RegisterBind[T any](fn func(*http.Request) (T, error))
- func RegisterOpenAPIFragment(id string, jsonDoc []byte)
- func RegisterOpenAPIFragmentString(id string, jsonDoc string)
- func RegisterWrite[T any](fn func(http.ResponseWriter, *http.Request, T) error)
- func ResetOpenAPIFragments()
- 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 SetOpenAPIInfo(info OpenAPIInfo) error
- func SetSocketDefaults(opts SocketOptions)
- func SetStreamErrorHandler(fn func(error))
- func SwaggerUI(specURL string) http.Handler
- func Unauthorized(problem Problem, cause ...error) error
- func Validation(fields ...FieldError) error
- func VaryAccept(w http.ResponseWriter)
- func WebSocket[In, Out any](w http.ResponseWriter, r *http.Request, fn func(*Socket[In, Out]) error) error
- func WebSocketWith[In, Out any](w http.ResponseWriter, r *http.Request, opts SocketOptions, ...) error
- func Write[T any](w http.ResponseWriter, r *http.Request, value T) error
- func WriteCBORBytes(w http.ResponseWriter, status int, data []byte) error
- func WriteError(w http.ResponseWriter, r *http.Request, err error)
- func WriteJSONBytes(w http.ResponseWriter, status int, data []byte) error
- func WriteStatus[T any](w http.ResponseWriter, r *http.Request, status int, value T) error
- func WriteStream[T any](w http.ResponseWriter, r *http.Request, fn func(*Stream[T]) error)
- type Declaration
- type FieldError
- type File
- type HTTPError
- type OpenAPIInfo
- type Problem
- type QueryValues
- 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). // Same family as JSONL / NDJSON; not a single JSON array document. StreamNDJSON = bindcore.StreamNDJSON // StreamJSONArray is application/json as one JSON array document: // [obj1,obj2,...] with items appended incrementally and closed by Close. 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 template compiler's own default, and a project renaming one renames both.
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 enforced by ParseMultipartMap (1 MiB). Override with SetMaxMultipartBodyBytes. Without this, io.ReadAll / unrestricted ParseMultipartForm would accept arbitrarily large bodies inside tinybind-go alone.
const DefaultMultipartMaxMemory = bindcore.DefaultMultipartMaxMemory
DefaultMultipartMaxMemory is the maxMemory argument passed to http.Request.ParseMultipartForm (how much of the form stays in RAM before spilling file parts to temp files). This is not a body size cap; see DefaultMaxMultipartBodyBytes.
Variables ¶
This section is empty.
Functions ¶
func AcceptsCBOR ¶ added in v0.5.19
AcceptsCBOR reports whether the client asked for a CBOR response. Only an explicit application/cbor entry in Accept counts; wildcards keep the JSON default, so a browser's */* never flips the response format.
func ActionSelector ¶ added in v0.5.8
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 because a submit button's formaction is what carries the selector when one form dispatches to several handlers, and that channel has to win over the form's own hidden field rather than merely coexist with it.
The value is compared as one opaque key by the caller, so no mismatch between the hash half and the name half is representable.
func AppendFileJSON ¶ added in v0.4.0
AppendFileJSON appends an uploaded file the way encoding/json rendered it before generated encoders stopped going through reflection: exported fields in declaration order, with the content base64-encoded.
func AssembleOpenAPI ¶ added in v0.1.11
AssembleOpenAPI merges every registered package fragment and returns a deterministic OpenAPI 3.1 JSON document.
func BadRequest ¶
BadRequest returns a 400 Bad Request error.
func Bind ¶
Bind maps an HTTP request into a typed request value. Dispatch uses a registry of generated binders; field mapping does not use reflect.
func CheckDateTime ¶
CheckDateTime reports whether s is RFC3339 (fractional seconds accepted).
func CheckEmail ¶
CheckEmail reports whether s is a pragmatic (non-RFC5322) email. Empty string returns false; callers skip empty optional fields before calling.
func CookieValue ¶
CookieValue returns a cookie value if present.
func DispatchAction ¶ added in v0.5.8
func DispatchAction(w http.ResponseWriter, r *http.Request, handler http.HandlerFunc)
DispatchAction runs one server function on the page's own POST route and applies the post-redirect-get default.
A handler that writes nothing gets a 303 back to the page it was submitted from, so a reload does not resubmit and the address bar keeps showing the page. A handler that writes a status, a header, or a body keeps exactly that response, which is what lets it redirect elsewhere, render the page inline with validation errors, or stream.
The direct entry point of a server function adds no redirect: there the handler's output is the response verbatim. The two entry points therefore differ in what a silent handler means, which is deliberate and documented, because only the form entry point has a page to go back to.
func HeaderValue ¶
HeaderValue returns a request header.
func IsCBORRequest ¶ added in v0.5.19
IsCBORRequest reports whether the request body should be treated as CBOR. Matches application/cbor and *+cbor types (RFC 6839).
func IsJSONRequest ¶
IsJSONRequest reports whether the request body should be treated as JSON. Matches application/json, text/json, and *+json types such as application/problem+json (RFC 7807 / RFC 9457).
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 OpenAPIDocument ¶ added in v0.5.2
OpenAPIDocument returns the assembled document, reusing the previous result until a fragment or info registration invalidates it.
It names no transport, so a second backend serves the document without reassembling it per request: a fragment registration cannot be observed from outside this package, which is what left a caller on another transport with AssembleOpenAPI and no way to cache the result itself.
The returned slice is shared with every other caller and must not be modified.
func OpenAPIJSON ¶
func OpenAPIJSON(w http.ResponseWriter, r *http.Request)
OpenAPIJSON serves the assembled OpenAPI document as application/json.
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 ¶
ParseFormMap parses 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 ¶
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 request body is capped at MaxMultipartBodyBytes() so tinybind-go itself enforces a size limit (default 1 MiB): Content-Length is checked when known, r.Body is wrapped with http.MaxBytesReader, and per-file reads use LimitReader. Oversized bodies and oversize file parts map to HTTP 413.
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 PayloadTooLarge ¶
PayloadTooLarge returns a 413 Payload Too Large error.
func QueryLookup ¶ added in v0.4.3
func QueryLookup(q QueryValues, key string) (string, bool)
QueryLookup returns the first value for key from pre-parsed query values.
func QueryValue ¶
QueryValue returns the first query parameter value for key. It scans the raw query for that one key rather than materializing every pair the way r.URL.Query() would.
func ReadActionBody ¶ added in v0.5.10
ReadActionBody reads the JSON payload of a typed server action call, under the configured body limit.
A generated wrapper calls this rather than reading the body itself, so the limit and the error mapping live in one place instead of being written into every emitted entry point.
func ReadCBORBody ¶ added in v0.5.19
ReadCBORBody reads the whole request body, bounded by MaxCBORBodyBytes. Decoding is the generated caller's: the bytes handed back are unparsed, and the decoder bounds its own walk by the same limit this read enforced.
func ReadFormBody ¶ added in v0.5.21
func ReadFormBody(r *http.Request, 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
ReadJSONBody reads the raw JSON body under MaxJSONBodyBytes. Generated binders parse the returned bytes in a single inline pass.
func ReadJSONBodyOwned ¶ added in v0.5.21
ReadJSONBodyOwned is ReadJSONBody under the name the transport pair needs: here the read buffer is always freshly owned, while the fasthttp runtime's version copies out of the pooled request. A binder that lets raw body bytes outlive the bind — a json.RawMessage field or rest map — is emitted against this name on both transports.
func Redirect ¶ added in v0.5.11
Redirect returns a value that sends the browser to target, travelling the error return because a caller returning values holds no ResponseWriter.
WriteError recognizes it and emits the status with a Location header instead of a problem document. The status defaults to 303; pass one of 301, 302, 307, or 308 to choose another.
It is an ordinary error value, so a page function, a handler, and a template's failing external all express a redirect the same way.
func RegisterBind ¶
RegisterBind registers a generated binder for T. Call from generated init(); field mapping lives entirely inside fn.
func RegisterOpenAPIFragment ¶ added in v0.1.11
RegisterOpenAPIFragment registers a generated package fragment. ID should be the package import path. Assembly reports conflicting repeated IDs.
func RegisterOpenAPIFragmentString ¶ added in v0.4.3
RegisterOpenAPIFragmentString is RegisterOpenAPIFragment for a string document. Generated code registers its embedded fragment constant through this so the constant is stored as-is, without a startup copy.
func RegisterWrite ¶
RegisterWrite registers a generated writer for T.
func ResetOpenAPIFragments ¶ added in v0.1.11
func ResetOpenAPIFragments()
ResetOpenAPIFragments clears registered fragments. It is intended for tests.
func RestFormAny ¶
RestFormAny builds map[string]any from leftover form keys not in exclude (string values).
func RestFormRaw ¶
RestFormRaw builds map[string]json.RawMessage from leftover form keys (JSON-encoded strings).
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 used by ParseMultipartMap (and generated binders). The limit wraps r.Body with http.MaxBytesReader and bounds per-file reads.
The value lives in bindcore, so a process setting it once configures every transport runtime rather than only the one it happened to call.
n > 0 → use n bytes n <= 0 → restore DefaultMaxMultipartBodyBytes (1 MiB)
func SetOpenAPIInfo ¶ added in v0.1.11
func SetOpenAPIInfo(info OpenAPIInfo) error
SetOpenAPIInfo sets application-level metadata for the assembled document. Repeating the same value is harmless; a different second value is an error.
func SetSocketDefaults ¶ added in v0.5.4
func SetSocketDefaults(opts SocketOptions)
SetSocketDefaults installs the process-wide socket options. It is shared with the fasthttp runtime, so installing them once covers both.
func SetStreamErrorHandler ¶ added in v0.4.9
func SetStreamErrorHandler(fn func(error))
SetStreamErrorHandler installs the destination for stream failures that happen after the response status has been sent. Passing nil discards them, which is the default: a runtime that logged on its own would be writing to a destination the caller did not choose.
The handler is shared with the fasthttp runtime, so installing it once covers both.
func SwaggerUI ¶
SwaggerUI returns an http.Handler that serves a minimal Swagger UI page loading the OpenAPI document from specURL (e.g. "/openapi.json").
Assets are loaded from a public CDN; this handler does not embed Swagger UI binaries. Mount freely, e.g.:
mux.Handle("GET /docs/{$}", httpbind.SwaggerUI("/openapi.json"))
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(w http.ResponseWriter)
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](w http.ResponseWriter, r *http.Request, fn func(*Socket[In, Out]) error) error
WebSocket upgrades the request, runs fn against a typed socket, and closes the socket when fn returns.
Handler usage:
_ = httpbind.WebSocket(w, r, func(s *httpbind.Socket[ClientMsg, ServerMsg]) error {
for {
in, err := s.Read()
if err != nil {
return err
}
if err := s.Write(ServerMsg{Type: "echo", Text: in.Text}); err != nil {
return err
}
}
})
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; the handler logs or counts it rather than answering. fn's own error is raised after the 101 has gone out, on this transport and on fasthttp, so it reaches the handler installed with SetStreamErrorHandler instead.
fn runs before this returns here and after the handler returns on fasthttp. Nothing in the callback may read the request, so that one source works on both: capture what it needs — the identity, the peer — before calling.
func WebSocketWith ¶ added in v0.5.4
func WebSocketWith[In, Out any](w http.ResponseWriter, r *http.Request, opts SocketOptions, fn func(*Socket[In, Out]) error) error
WebSocketWith is WebSocket with per-call options, for the endpoint whose limits or cadence differ from the process defaults.
func Write ¶
Write serializes a typed response value to the HTTP 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 is tried first, for the reason jsonbind.EncodeJSON states: a type that carries a method has an author-written encoder, and going through a generated one instead would produce bytes they did not intend. It is also what lets a value from a package this build never analyzed be answered with at all, which no registration could reach.
func WriteCBORBytes ¶ added in v0.5.19
func WriteCBORBytes(w http.ResponseWriter, 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(w http.ResponseWriter, r *http.Request, err error)
WriteError writes err as an RFC 9457 Problem Details response. Internal causes are not exposed in the client body.
JSON is written without encoding/json for the problem document so TinyGo does not hit unimplemented reflect.AssignableTo when binders also use json.RawMessage (a known interaction in TinyGo's encoding/json). The document itself is derived in bindcore, so the other transport runtime writes the same bytes for the same error rather than reimplementing the rule.
func WriteJSONBytes ¶ added in v0.4.0
func WriteJSONBytes(w http.ResponseWriter, 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 ¶
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 ¶ added in v0.4.9
WriteStream opens a negotiated stream, runs fn against it, and closes it.
It returns nothing. fn runs after the handler has returned on the fasthttp runtime, where an error cannot travel back to handler code, so neither surface offers one and the same handler source works on both.
A failure to open — before any byte is committed — becomes an ordinary Problem response. Once the stream is open the status is already sent, so an error from fn reaches the handler installed with SetStreamErrorHandler instead. Close runs either way, which is what keeps a JSON array document terminated when fn fails halfway through it.
Types ¶
type Declaration ¶ added in v0.5.10
type Declaration struct{}
Declaration is what ServerAction returns. It carries nothing: the value exists only so the annotation can be written as a package-level declaration, which is where generation reads it.
func ServerAction ¶ added in v0.5.10
func ServerAction(fn any, name ...string) Declaration
ServerAction declares that fn is a server action reachable from client script, whatever its signature.
A handler-shaped function is an action by existing, because that shape is unambiguous: an exported function taking the transport types and returning nothing is nothing else. An arbitrary signature distinguishes nothing, since every function has one, so something outside the signature has to say which functions are actions. That is what this declaration is for, and it is the only thing it does.
Write it at package level, beside the function:
var _ = httpbind.ServerAction(GetUser)
fn is taken as a symbol rather than as a name string, so a declaration naming something that does not exist fails to compile before generation reads it.
The optional name is the identifier client script calls through. Without one it is derived from the Go name in initialism-aware lowerCamelCase, so GetUser is reached as getUser and URLFor as urlFor. Supply one for a name the derivation reads wrong, or for a published name a Go rename must not move: like a struct tag, it is a wire name rather than a second identity.
The call runs at init and does nothing. The declaration is the point.
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 ¶
File is an uploaded file bound from a multipart/form-data part. After a successful bind, Filename, ContentType (when the client sent one), Size, and Content are populated from the named file part.
It is an alias so a model struct declaring a File field compiles against either transport runtime without naming one of them.
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 OpenAPIInfo ¶ added in v0.1.11
OpenAPIInfo is application-owned metadata for the assembled document.
type QueryValues ¶ added in v0.5.21
type QueryValues struct {
// contains filtered or unexported fields
}
QueryValues is the request's query string split once into raw key=value spans, in wire order.
Generated binders only ever ask for a key's first value, so the url.Values map — one allocation per key plus an unescaped copy of every member — buys random access nobody uses. Splitting into spans costs one slice, and a span is unescaped only when it is actually looked up and actually escaped: the same trade the binders' inline JSON walk makes for body members.
func Queries ¶ added in v0.4.3
func Queries(r *http.Request) QueryValues
Queries parses the request's query string once. Generated binders call this a single time per request and resolve each field with QueryLookup, instead of re-parsing the raw query per field the way QueryValue does.
type Socket ¶ added in v0.5.4
Socket is a typed WebSocket connection: Read decodes into In, Write encodes from Out, both through the jsonbind codec registry.
It is the same type the fasthttp runtime uses, so a callback body compiles unchanged on either transport. In and Out must each have a generated codec — a decoder for In, an encoder for Out — which discovery emits from the two type arguments of the WebSocket call.
Read must be called from one goroutine. Write may be called from any.
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, and nothing reaches the driver as zero.
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.
Handler usage:
httpbind.WriteStream(w, r, func(s *httpbind.Stream[ChatEvent]) error {
if err := s.Write(ChatEvent{Type: "delta", Delta: "hi"}); err != nil {
return err
}
return s.Write(ChatEvent{Type: "done"})
})
Format (SSE vs NDJSON vs JSON array) is chosen once by rule:stream-content-negotiation. Write may be called many times; headers and status are sent when the stream opens. WriteStream closes the stream, which is what writes the trailing ']' of the JSON array framing.
The framing lives in one place shared with the fasthttp runtime, so the same events produce the same bytes on either transport.
Events are encoded through the jsonbind codec registry: T must have a generated encoder (or one registered manually via jsonbind.RegisterEncode).
type StreamFormat ¶
type StreamFormat = bindcore.StreamFormat
StreamFormat is the negotiated on-the-wire format for Stream[T].
func NegotiateStreamFormat ¶
func NegotiateStreamFormat(r *http.Request) StreamFormat
NegotiateStreamFormat selects SSE, NDJSON, or JSON array using:
- ?stream= query
- Accept
- User-Agent heuristics
- default NDJSON
Exported for tests and advanced callers.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package cachekeybind provides typed, reflection-free cache key generation.
|
Package cachekeybind provides typed, reflection-free cache key generation. |
|
Package cborbind generates CBOR codecs for the types its entry points name.
|
Package cborbind generates CBOR codecs for the types its entry points name. |
|
Package cliparser parses argv into a map of stable config keys using precomputed flag definitions.
|
Package cliparser parses argv into a map of stable config keys using precomputed flag definitions. |
|
cmd
|
|
|
tinybind-gen
command
|
|
|
Package configbind loads Bind-style config from defaults, TOML, env, and CLI into structs.
|
Package configbind loads Bind-style config from defaults, TOML, env, and CLI into structs. |
|
codegen
Package codegen emits reflection-free configbind apply, flag, and env key tables.
|
Package codegen emits reflection-free configbind apply, flag, and env key tables. |
|
Package configpath resolves one config file path for configbind.
|
Package configpath resolves one config file path for configbind. |
|
Package dynamobind provides typed, reflection-free DynamoDB item binding on top of github.com/shibukawa/tinygodriver/nosql/dynamodb.
|
Package dynamobind provides typed, reflection-free DynamoDB item binding on top of github.com/shibukawa/tinygodriver/nosql/dynamodb. |
|
examples
|
|
|
demo
command
|
|
|
websocket
command
Command websocket serves a typed WebSocket chat room beside ordinary REST routes on one port, under both compilers.
|
Command websocket serves a typed WebSocket chat room beside ordinary REST routes on one port, under both compilers. |
|
Package fasthttpbind is the fasthttp half of the binding runtime.
|
Package fasthttpbind is the fasthttp half of the binding runtime. |
|
Package fasthttpupdate is the fasthttp half of the partial-update surface.
|
Package fasthttpupdate is the fasthttp half of the partial-update surface. |
|
Package firestorebind provides typed, reflection-free entity binding for Firestore in Datastore mode, on top of github.com/shibukawa/tinygodriver/nosql/datastore.
|
Package firestorebind provides typed, reflection-free entity binding for Firestore in Datastore mode, on top of github.com/shibukawa/tinygodriver/nosql/datastore. |
|
Package htmlbind is the rendering runtime for generated HTML templates.
|
Package htmlbind is the rendering runtime for generated HTML templates. |
|
delta
Package delta compares two renders of one chain and expresses the difference as operations a browser applies, so a screen already showing the document reaches the server's fresh render without a full page load.
|
Package delta compares two renders of one chain and expresses the difference as operations a browser applies, so a screen already showing the document reaches the server's fresh render without a full page load. |
|
Package htmlupdate serves HTML templates that can update themselves in place.
|
Package htmlupdate serves HTML templates that can update themselves in place. |
|
internal
|
|
|
benchfixture
Package benchfixture backs the benchmark table in the project README.
|
Package benchfixture backs the benchmark table in the project README. |
|
bindcore
Package bindcore holds the declarations both transport runtimes need and neither should own: the error model, the uploaded-file value, and the check helpers.
|
Package bindcore holds the declarations both transport runtimes need and neither should own: the error model, the uploaded-file value, and the check helpers. |
|
dynamofixture
Package dynamofixture exercises the generated DynamoDB item codec against the dynamobind runtime and the driver's wire protocol.
|
Package dynamofixture exercises the generated DynamoDB item codec against the dynamobind runtime and the driver's wire protocol. |
|
externalscan
Package externalscan reads the Go signatures of the package-level functions a template may call as externals, and reports the two things generation cannot learn from the template: which take a leading context.Context, and which return a trailing error.
|
Package externalscan reads the Go signatures of the package-level functions a template may call as externals, and reports the two things generation cannot learn from the template: which take a leading context.Context, and which return a trailing error. |
|
fasthttppagesfixture/pages/raw
Package raw is the rung 3 route: a page whose Load owns the whole response.
|
Package raw is the rung 3 route: a page whose Load owns the whole response. |
|
firestorefixture
Package firestorefixture exercises the generated Firestore entity codec against the firestorebind runtime and the driver's wire protocol.
|
Package firestorefixture exercises the generated Firestore entity codec against the firestorebind runtime and the driver's wire protocol. |
|
gensource
Package gensource identifies the Go files a generation run wrote.
|
Package gensource identifies the Go files a generation run wrote. |
|
godoc
Package godoc extracts documentation text from Go doc comments so host-side analysis can carry it into generated artifacts such as OpenAPI descriptions.
|
Package godoc extracts documentation text from Go doc comments so host-side analysis can carry it into generated artifacts such as OpenAPI descriptions. |
|
linedirective
Package linedirective builds the Go //line comments that map generated template code back to the template that produced it.
|
Package linedirective builds the Go //line comments that map generated template code back to the template that produced it. |
|
pagesfixture/pages/archive
Package archive is the route that needs the request itself rather than the address it was sent to.
|
Package archive is the route that needs the request itself rather than the address it was sent to. |
|
pagesfixture/pages/records/id_
Package id_ serves one record with no typed entry point.
|
Package id_ serves one record with no typed entry point. |
|
updatecore
Package updatecore is the transport-free half of the partial-update surface.
|
Package updatecore is the transport-free half of the partial-update surface. |
|
Package jsonbind provides generated, reflection-free JSON document codecs.
|
Package jsonbind provides generated, reflection-free JSON document codecs. |
|
Package minitoml parses a restricted TOML subset into a flat intermediate key/value form.
|
Package minitoml parses a restricted TOML subset into a flat intermediate key/value form. |
|
codegen
Package codegen emits reflection-free apply functions from intermediate minitoml.Document keys.
|
Package codegen emits reflection-free apply functions from intermediate minitoml.Document keys. |
|
Package routetree discovers a filesystem route tree and derives the stdlib ServeMux patterns, ancestor layout chains, and Go package names for it.
|
Package routetree discovers a filesystem route tree and derives the stdlib ServeMux patterns, ancestor layout chains, and Go package names for it. |
|
Package sqlbind provides generated, reflection-free database/sql row mapping.
|
Package sqlbind provides generated, reflection-free database/sql row mapping. |
|
templates
|
|
|
dynamobind
Package dynamobind parses and prints typed DynamoDB access-pattern sources.
|
Package dynamobind parses and prints typed DynamoDB access-pattern sources. |
|
firestorebind
Package firestorebind parses and prints typed Firestore Datastore access-pattern sources.
|
Package firestorebind parses and prints typed Firestore Datastore access-pattern sources. |
|
htmlbind
Package htmlbind parses typed HTML template sources into an AST.
|
Package htmlbind parses typed HTML template sources into an AST. |
|
internal/rawparse
Package rawparse provides the lossless dummy format parser used to exercise the shared template parser without HTML or SQL knowledge.
|
Package rawparse provides the lossless dummy format parser used to exercise the shared template parser without HTML or SQL knowledge. |
|
sqlbind
Package sqlbind parses and compiles typed SQL template sources.
|
Package sqlbind parses and compiles typed SQL template sources. |
|
templatefmt
Package templatefmt formats tinybind template sources.
|
Package templatefmt formats tinybind template sources. |