Documentation
¶
Index ¶
- func Call[I any, O any](r *Router, ctx context.Context, path string, input I) (O, error)
- func GetResponseCookies(ctx context.Context) []*http.Cookie
- func GetResponseHeaders(ctx context.Context) http.Header
- func HTTPStatusFromCode(code ErrorCode) int
- func Mutation[I any, O any](r *Router, path string, fn func(ctx context.Context, input I) (O, error), ...)
- func NameFromCode(code ErrorCode) string
- func Query[I any, O any](r *Router, path string, fn func(ctx context.Context, input I) (O, error), ...)
- func SetCookie(ctx context.Context, c *http.Cookie)
- func SetResponseHeader(ctx context.Context, key, value string)
- func Subscribe[I any, O any](r *Router, path string, ...)
- func VoidMutation[O any](r *Router, path string, fn func(ctx context.Context) (O, error), ...)
- func VoidQuery[O any](r *Router, path string, fn func(ctx context.Context) (O, error), ...)
- func VoidSubscribe[O any](r *Router, path string, fn func(ctx context.Context) (<-chan O, error), ...)
- func WithResponseMetadata(ctx context.Context) context.Context
- type Error
- type ErrorCode
- type ErrorFormatterInput
- type HandlerFunc
- type Middleware
- type Option
- func WithBatching(enabled bool) Option
- func WithContextCreator(fn func(r *http.Request) context.Context) Option
- func WithDev(enabled bool) Option
- func WithErrorFormatter(fn func(ErrorFormatterInput) any) Option
- func WithMaxBatchSize(n int) Option
- func WithMaxBodySize(n int64) Option
- func WithMethodOverride(enabled bool) Option
- func WithOnError(fn func(ctx context.Context, err *Error, path string)) Option
- func WithSSEMaxDuration(d time.Duration) Option
- func WithSSEPingInterval(d time.Duration) Option
- func WithSSEReconnectAfterInactivity(d time.Duration) Option
- func WithTypeOutput(path string) Option
- func WithValidator(fn func(any) error) Option
- func WithZodMini(enabled bool) Option
- func WithZodOutput(path string) Option
- type ProcedureMeta
- type ProcedureOption
- type ProcedureType
- type Router
- type TrackedEvent
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Call ¶
Call invokes a typed procedure by path, running the full middleware chain. Input is marshaled to JSON and the result is unmarshaled to the output type.
func GetResponseCookies ¶
GetResponseCookies returns the cookies collected in the context by SetCookie. This is useful for RawCall callers that need to inspect cookies set by handlers. Returns nil if the context does not carry response metadata.
func GetResponseHeaders ¶
GetResponseHeaders returns the headers collected in the context by SetResponseHeader. This is useful for RawCall callers that need to inspect headers set by handlers. Returns nil if the context does not carry response metadata.
func HTTPStatusFromCode ¶
HTTPStatusFromCode returns the HTTP status code for a tRPC error code.
func Mutation ¶
func Mutation[I any, O any](r *Router, path string, fn func(ctx context.Context, input I) (O, error), opts ...ProcedureOption)
Mutation registers a mutation procedure.
func NameFromCode ¶
NameFromCode returns the string name for a tRPC error code (e.g. "NOT_FOUND").
func Query ¶
func Query[I any, O any](r *Router, path string, fn func(ctx context.Context, input I) (O, error), opts ...ProcedureOption)
Query registers a query procedure.
func SetCookie ¶
SetCookie adds a cookie to be set on the HTTP response. Call this from within a procedure handler or middleware. If the context does not carry response metadata (e.g. called outside the HTTP handler), this is a no-op. Safe for concurrent use from JSONL batch handlers.
func SetResponseHeader ¶
SetResponseHeader adds a header value to be set on the HTTP response. If the context does not carry response metadata, this is a no-op. Safe for concurrent use from JSONL batch handlers.
func Subscribe ¶
func Subscribe[I any, O any](r *Router, path string, fn func(ctx context.Context, input I) (<-chan O, error), opts ...ProcedureOption)
Subscribe registers a subscription procedure.
func VoidMutation ¶
func VoidMutation[O any](r *Router, path string, fn func(ctx context.Context) (O, error), opts ...ProcedureOption)
VoidMutation registers a mutation procedure with no input.
func VoidQuery ¶
func VoidQuery[O any](r *Router, path string, fn func(ctx context.Context) (O, error), opts ...ProcedureOption)
VoidQuery registers a query procedure with no input.
func VoidSubscribe ¶
func VoidSubscribe[O any](r *Router, path string, fn func(ctx context.Context) (<-chan O, error), opts ...ProcedureOption)
VoidSubscribe registers a subscription procedure with no input.
func WithResponseMetadata ¶
WithResponseMetadata injects a fresh responseMetadata into the context. This is called automatically by the HTTP handler. For RawCall, callers should call this before RawCall if they need to access cookies/headers set by handlers via GetResponseCookies/GetResponseHeaders.
Types ¶
type Error ¶
Error represents a tRPC error with a JSON-RPC 2.0 error code.
type ErrorCode ¶
type ErrorCode int
ErrorCode represents JSON-RPC 2.0 error codes used by the tRPC wire protocol.
const ( CodeParseError ErrorCode = -32700 CodeBadRequest ErrorCode = -32600 CodeInternalServerError ErrorCode = -32603 CodeForbidden ErrorCode = -32003 CodeNotFound ErrorCode = -32004 CodeMethodNotSupported ErrorCode = -32005 CodeTimeout ErrorCode = -32008 CodeConflict ErrorCode = -32009 CodePreconditionFailed ErrorCode = -32012 CodePayloadTooLarge ErrorCode = -32013 CodeUnsupportedMedia ErrorCode = -32015 CodeUnprocessableContent ErrorCode = -32022 CodePreconditionRequired ErrorCode = -32028 CodeTooManyRequests ErrorCode = -32029 CodeClientClosed ErrorCode = -32099 CodeNotImplemented ErrorCode = -32501 CodeBadGateway ErrorCode = -32502 CodeGatewayTimeout ErrorCode = -32504 )
type ErrorFormatterInput ¶
type ErrorFormatterInput struct {
Error *Error
Type ProcedureType
Path string
Ctx context.Context
Shape errorEnvelope // the default tRPC error shape
}
ErrorFormatterInput is passed to a custom error formatter. It includes the default error shape so the formatter can extend or replace it.
type HandlerFunc ¶
HandlerFunc is the procedure handler signature. The input parameter is the already-decoded struct (or nil for void procedures). Middleware receives the same decoded input — no json.RawMessage at any layer.
type Middleware ¶
type Middleware func(next HandlerFunc) HandlerFunc
Middleware wraps a procedure handler, enabling cross-cutting concerns like logging, authentication, and error handling.
func Chain ¶
func Chain(mws ...Middleware) Middleware
Chain composes multiple middleware into one, applied left-to-right.
type Option ¶
type Option func(*routerOptions)
Option configures a Router.
func WithBatching ¶
WithBatching enables or disables batch request support.
func WithContextCreator ¶
WithContextCreator sets a function that creates the base context for each request.
func WithDev ¶
WithDev enables development mode. When true, error responses include Go stack traces in the data.stack field, matching tRPC's isDev behavior.
func WithErrorFormatter ¶
func WithErrorFormatter(fn func(ErrorFormatterInput) any) Option
WithErrorFormatter sets a custom error formatter that transforms error responses. The function receives the default error shape and can return a modified or entirely different shape. This matches tRPC's errorFormatter.
func WithMaxBatchSize ¶
WithMaxBatchSize sets the maximum number of procedures allowed in a single batch request. Default is 10. Set to 0 for no limit.
func WithMaxBodySize ¶
WithMaxBodySize sets the maximum allowed request body size in bytes. Default is 1 MB. Set to 0 for no limit.
func WithMethodOverride ¶
WithMethodOverride allows clients to override HTTP method (send queries as POST).
func WithOnError ¶
WithOnError sets a callback invoked when a procedure returns an error.
func WithSSEMaxDuration ¶
WithSSEMaxDuration sets the maximum duration for SSE subscriptions. Default is 0 (unlimited).
func WithSSEPingInterval ¶
WithSSEPingInterval sets the keep-alive ping interval for SSE subscriptions. Default is 10 seconds.
func WithSSEReconnectAfterInactivity ¶
WithSSEReconnectAfterInactivity tells the client to reconnect after the given duration of inactivity. This is sent in the SSE connected event as reconnectAfterInactivityMs, matching tRPC's protocol. Default is 0 (disabled).
func WithTypeOutput ¶
WithTypeOutput enables automatic TypeScript type generation. When set, calling Router.Handler() writes the TypeScript AppRouter type file to the given path. Use with the top-level registration functions (Query, Mutation, Subscribe, etc.) to capture type info.
func WithValidator ¶
WithValidator sets a function that validates procedure inputs. The function is called with the deserialized input struct after JSON unmarshaling. Only struct-typed inputs are validated; primitives are skipped.
This matches go-playground/validator directly — pass validate.V.Struct:
router := trpcgo.NewRouter(trpcgo.WithValidator(validate.V.Struct))
func WithZodMini ¶
WithZodMini switches Zod schema output to zod/mini functional syntax. Only has effect when WithZodOutput is also set.
func WithZodOutput ¶
WithZodOutput enables automatic Zod schema generation alongside TypeScript types. Requires WithTypeOutput to be set. The file watcher regenerates both files when Go source changes are detected.
type ProcedureMeta ¶
type ProcedureMeta struct {
Path string
Type ProcedureType
Meta any // user-defined metadata from WithMeta()
}
ProcedureMeta contains procedure metadata available to middleware via context. Use GetProcedureMeta(ctx) to read it inside middleware.
func GetProcedureMeta ¶
func GetProcedureMeta(ctx context.Context) (ProcedureMeta, bool)
GetProcedureMeta returns the procedure metadata from the context. Returns false if not available (e.g., outside a procedure call).
type ProcedureOption ¶
type ProcedureOption func(*procedureConfig)
ProcedureOption configures a single procedure registration.
func WithMeta ¶
func WithMeta(meta any) ProcedureOption
WithMeta attaches metadata to a procedure, accessible in middleware via GetProcedureMeta(ctx).
type ProcedureType ¶
type ProcedureType string
ProcedureType distinguishes queries, mutations, and subscriptions.
const ( ProcedureQuery ProcedureType = "query" ProcedureMutation ProcedureType = "mutation" ProcedureSubscription ProcedureType = "subscription" )
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router holds registered procedures and produces an http.Handler implementing the tRPC HTTP wire protocol.
func MergeRouters ¶
MergeRouters creates a new Router combining procedures from all sources. Panics if any two routers define a procedure at the same path. The returned router has default options and no global middleware.
func (*Router) GenerateTS ¶
GenerateTS writes TypeScript type definitions for all registered procedures. Procedures must be registered via the top-level functions (Query, Mutation, etc.) to have type information available.
func (*Router) Handler ¶
Handler returns an http.Handler that serves all registered procedures. basePath is stripped from incoming request URLs before procedure lookup.
If WithTypeOutput was configured, the TypeScript type file is written and a file watcher is started to regenerate types when Go source changes.
func (*Router) Merge ¶
Merge copies all procedures from the source routers into this router. Panics if any procedure path already exists. Global middleware and options on source routers are NOT copied.
func (*Router) RawCall ¶
RawCall invokes a procedure by path, running the full middleware chain. This is the server-side equivalent of an HTTP call — no network involved.
Subscriptions are not supported via RawCall; use the subscription handler directly.
func (*Router) Use ¶
func (r *Router) Use(mw ...Middleware)
Use adds global middleware that applies to all procedures.
type TrackedEvent ¶
TrackedEvent wraps a value with an ID for SSE reconnection support. When the client disconnects and reconnects, it sends the last received ID back in the input (as lastEventId), allowing the handler to resume from where it left off.
func Tracked ¶
func Tracked[T any](id string, data T) TrackedEvent[T]
Tracked creates a TrackedEvent that associates an ID with data. The ID is sent as the SSE id field, enabling client reconnection.