Documentation
¶
Overview ¶
Package fuge Package asyncapi3 emits AsyncAPI 3.1.0 documents from Go code.
Declare servers, channels, and operations as Go values, reflect payload schemas from the structs that cross the wire with SchemaFromType, and marshal the Document to JSON or YAML.
Marshalled output is deterministic — maps marshal key-sorted and struct field order is fixed — so regenerating an unchanged document is byte-identical. That property is what makes a committed document gateable in CI; see Check.
The document model is a curated subset of the specification. Spec objects and protocol bindings it does not model yet attach as raw JSON through the Bindings fields, so an unmodelled binding never blocks you.
Package fuge is a typed RPC layer for Centrifuge WebSocket connections, documented as it's built. Register a typed Go function and it becomes both a live RPC method and an entry in the generated AsyncAPI 3.1 document — the way huma binds an HTTP handler and documents it as OpenAPI in one call.
The package works at three layers, and most applications only ever touch the top one:
- Register / Operation / Group: bind a typed handler and describe it (summary, tags, security, error codes, "x-" extensions). This is what builds the AsyncAPI document, and it's the primary, recommended way to add a method.
- Handle / RouteGroup (on API or Router): register a raw, undocumented method directly — an escape hatch for internal methods that shouldn't appear in the public document.
- Router: the underlying dispatcher (middleware, timeouts, panic recovery, bounded concurrency, Centrifuge wiring). API embeds one; most applications never construct a Router directly.
Getting started ¶
api := fuge.New(fuge.DefaultConfig("Platform RPC", "1.0.0"))
fuge.Register(api, fuge.Operation{
OperationID: "create-country",
Method: "country.create",
Summary: "Create a new country",
}, func(ctx context.Context, req *CreateCountryRequest) (*Country, error) {
return &Country{ID: 1, Name: req.Name}, nil
})
node.OnConnect(func(c *centrifuge.Client) { api.Attach(node, c) })
api.ServeDocs(mux) // /asyncapi.json, /asyncapi.yaml, interactive /asyncdocs/ (paths: Config.DocsPath etc.)
Errors ¶
A handler can return a plain error (mapped to an internal error and logged, never leaking details to the client), a *fuge.Error built with NewError or one of ErrNotFound / ErrConflict / ErrValidation / ErrTimeout (mapped to its Code/Message/Temporary), or a *centrifuge.Error directly. WithErrorMapper translates domain errors (e.g. a database's "not found") without every handler needing to know about them.
Documenting a method ¶
Operation mirrors huma.Operation. Security is a list of alternative requirements — each map is one set of schemes that together satisfy the operation (an "AND"); the list itself is the "OR". AsyncAPI 3 cannot express an "AND" inside one requirement (unlike OpenAPI), so a map with more than one entry panics at registration. Extensions are "x-" keys merged onto the operation. Errors are extra Centrifuge error codes the operation may return, beyond the internal/bad-request/validation codes added automatically.
Channels: real Centrifuge pub/sub, not RPC ¶
Register documents a synthetic "rpc.<method>" channel purely so every RPC method has somewhere to hang its schemas in the document; it has nothing to do with Centrifuge's actual channel/subscribe mechanism. For a real channel — one clients subscribe to, that the server (or another client, or another service acting as one) publishes into — use RegisterChannel:
notif := fuge.RegisterChannel[Notification](api, fuge.Channel{
ID: "user-notifications", Pattern: "user:{userId}:notifications",
})
notif.OnSubscribe(func(ctx context.Context, params fuge.Params, info fuge.SubscribeInfo) error {
if params["userId"] != info.UserID {
return centrifuge.ErrorPermissionDenied
}
return nil
})
notif.Publish(node, fuge.Params{"userId": user.ID}, Notification{Text: "..."})
Centrifuge itself has no notion of "declared" channels — by default any client can subscribe to any string. API.Attach closes that gap: a subscribe to an address matching no RegisterChannel'd pattern is rejected with centrifuge.ErrorUnknownChannel before OnSubscribe ever runs.
Publish, similarly, is refused by Centrifuge unless explicitly allowed. AllowPublish opts a channel into it, and lets the publish shape differ from the broadcast shape — what a publisher sends isn't always what subscribers should receive:
fuge.AllowPublish(chatRoom, func(ctx context.Context, params fuge.Params, in *ChatInput) (*ChatMessage, error) {
return &ChatMessage{RoomID: params["roomId"], Author: fuge.InfoFrom(ctx).UserID, Text: in.Text}, nil
})
in is decoded and Validate()'d like an RPC request. Returning (nil, nil) accepts the publish without broadcasting anything.
Every operation fuge generates — RPC, broadcast, or publish — carries "x-fuge-operation-kind" ("rpc" / "broadcast" / "publish"), so a document consumer (a renderer, a future client generator) never has to guess intent from channel naming.
Index ¶
- Constants
- Variables
- func AllowPublish[T, Req any](ch *ChannelHandle[T], ...)
- func Check(generated []byte, path string) error
- func MergeSchemas(dst, src map[string]json.RawMessage) error
- func Register[Req, Res any](r Registrar, op Operation, ...)
- func SchemaFromType(v any, opts ...ReflectOption) (json.RawMessage, map[string]json.RawMessage, error)
- type API
- func (a *API) Attach(node *centrifuge.Node, c *centrifuge.Client)
- func (a *API) Call(ctx context.Context, method string, data []byte) ([]byte, error)
- func (a *API) DocsHandler(prefix string, opts ...DocsOptions) http.Handler
- func (a *API) DocsRoute() string
- func (a *API) DocsRoutes() []Route
- func (a *API) Document() *Document
- func (a *API) Group(prefix string, tags ...string) *Group
- func (a *API) Handle(method string, h Handler, opts ...RouteOption)
- func (a *API) JSON() ([]byte, error)
- func (a *API) JsonDocHandler() http.Handler
- func (a *API) JsonRoute() string
- func (a *API) RouteGroup(prefix string, mw ...Middleware) *RouteGroup
- func (a *API) Router() *Router
- func (a *API) Routes() []Route
- func (a *API) ServeDocs(m Mux)
- func (a *API) ServeSpec(m Mux)
- func (a *API) SpecRoutes() []Route
- func (a *API) Use(mw ...Middleware)
- func (a *API) UseChannelGate(g ...ChannelGate)
- func (a *API) UseMiddleware(mw ...OpMiddleware)
- func (a *API) YamlDocHandler() http.Handler
- func (a *API) YamlRoute() string
- type CallInfo
- type Channel
- type ChannelAction
- type ChannelGate
- type ChannelHandle
- type ChannelInfo
- type Codec
- type Components
- type Config
- type Contact
- type DocsOptions
- type Document
- type Error
- type ErrorMapper
- type Extensions
- type ExternalDocs
- type Group
- type Handler
- type Info
- type License
- type Logger
- type Message
- type Middleware
- type Mux
- type OAuthFlow
- type OAuthFlows
- type OAuthOptions
- type OpHandler
- type OpMiddleware
- type Operation
- type OperationReply
- type Option
- type Parameter
- type Params
- type RefObj
- type ReflectOption
- type Registrar
- type Request
- type Response
- type Route
- type RouteGroup
- type RouteOption
- type Router
- func (r *Router) Attach(c *centrifuge.Client)
- func (r *Router) Call(ctx context.Context, method string, data []byte) ([]byte, error)
- func (r *Router) Handle(method string, h Handler, opts ...RouteOption)
- func (r *Router) RouteGroup(prefix string, mw ...Middleware) *RouteGroup
- func (r *Router) Routes() []string
- func (r *Router) Use(mw ...Middleware)
- type SecurityScheme
- type Server
- type SpecChannel
- type SpecOperation
- type SubscribeInfo
- type Tag
- type Validator
Constants ¶
const ( ActionSend = "send" ActionReceive = "receive" )
SpecOperation actions, as defined by the specification: an application either sends a message to a channel or receives one from it. Both are expressed from the point of view of the application described by the document.
const ( CodeTimeout uint32 = 408 CodeNotFound uint32 = 404 CodeConflict uint32 = 409 CodeValidation uint32 = 422 )
Application error codes. Centrifuge reserves the low ranges for itself, so keep custom codes >= 400.
const ( SecurityTypeHTTP = "http" SecurityTypeHTTPAPIKey = "httpApiKey" SecurityTypeOAuth2 = "oauth2" SecurityTypeOpenIDConnect = "openIdConnect" )
Security scheme types fuge supports.
const ( ExtClientID = "x-fuge-client-id" ExtRedirectURI = "x-fuge-redirect-uri" ExtUsePKCE = "x-fuge-use-pkce" ExtDefaultScopes = "x-fuge-default-scopes" ExtTokenName = "x-fuge-token-name" ExtCredentialsLocation = "x-fuge-credentials-location" ExtAuthorizeParams = "x-fuge-authorize-params" ExtTokenParams = "x-fuge-token-params" )
Keys of the "x-fuge-*" extensions the docs UI reads from an oauth2 or openIdConnect SecurityScheme to pre-fill its authorization panel. Build them with OAuthExtensions.
const Version = "3.1.0"
Version is the AsyncAPI specification version this package emits: 3.1.0, the only version NewDocument emits.
Variables ¶
var ( ErrNotFound = NewError(CodeNotFound, "not found") ErrConflict = NewError(CodeConflict, "conflict") ErrValidation = NewError(CodeValidation, "validation failed") ErrTimeout = &Error{Code: CodeTimeout, Message: "request timed out", Temporary: true} )
Functions ¶
func AllowPublish ¶
func AllowPublish[T, Req any](ch *ChannelHandle[T], fn func(ctx context.Context, params Params, req *Req) (*T, error))
AllowPublish lets clients (including other services acting as ordinary Centrifuge clients) publish directly into ch, documenting a second, "receive" operation on the same channel. Req is what a publisher must send — decoded and Validate()'d exactly like an RPC request — and is deliberately allowed to differ from T, what subscribers receive: fn is the seam between them. Returning (nil, nil) accepts the publish without broadcasting anything.
func Check ¶
Check compares freshly generated document bytes against the committed artifact at path, so contract-drift gating runs as one tested code path locally and in CI instead of shell logic in a workflow.
func MergeSchemas ¶
func MergeSchemas(dst, src map[string]json.RawMessage) error
MergeSchemas folds src into dst, failing on same-name definitions with different content — a silent overwrite would corrupt one of the schemas.
func Register ¶
func Register[Req, Res any](r Registrar, op Operation, fn func(ctx context.Context, req *Req) (*Res, error))
Register binds a typed handler and documents it, mirroring huma.Register.
fuge.Register(api, fuge.Operation{
OperationID: "create-country",
Method: "country.create",
Summary: "Create a new country",
}, createCountry) // func(ctx, *CreateCountryRequest) (*Country, error)
Req and Res are inferred from the handler. Use struct{} for "no payload". Returning a nil *Res replies with no data. Misconfiguration (duplicate names, unknown security scheme, conflicting schemas) panics at startup.
func SchemaFromType ¶
func SchemaFromType(v any, opts ...ReflectOption) (json.RawMessage, map[string]json.RawMessage, error)
SchemaFromType reflects v into a JSON Schema, returning the payload schema for the value itself — a "$ref" into "#/components/schemas/" — and the definitions it references, ready to assign to Components.Schemas.
Property names come from json struct tags. Schema keywords are read from the tags jsonschema-go understands, including required:"true", so the wire contract is declared on the struct rather than restated here.
Types ¶
type API ¶
type API struct {
// contains filtered or unexported fields
}
API is the single object an application holds: it dispatches RPC calls (embedding a *Router) and, in the same step, documents every call Register binds as AsyncAPI. There is no separate router type to wire up — New builds both together.
func New ¶
New builds the API: a Router (configured by opts, see WithDefaultTimeout, WithMaxInflight, WithErrorMapper, WithLogger) plus the AsyncAPI document described by cfg. Use DefaultConfig to build cfg.
func (*API) Attach ¶
func (a *API) Attach(node *centrifuge.Node, c *centrifuge.Client)
Attach wires the API into a Centrifuge connection: Register'd RPC methods (via Router.Attach), plus subscribe/publish dispatch for every channel registered with RegisterChannel. node is required to actually publish a transformed message when a channel has AllowPublish set (see channels.go); call this from node.OnConnect, where both are already in scope together:
node.OnConnect(func(c *centrifuge.Client) { api.Attach(node, c) })
A subscribe to an address matching no registered channel is rejected with centrifuge.ErrorUnknownChannel — Centrifuge itself has no such restriction by default (see RegisterChannel's doc comment), so this is what makes "channels must be declared on the backend" actually true.
func (*API) DocsHandler ¶
func (a *API) DocsHandler(prefix string, opts ...DocsOptions) http.Handler
DocsHandler serves an interactive AsyncAPI reference: the rendered operations and schemas plus a "Try it" client that connects to the websocket, calls RPC methods and subscribes to channels. It is self-contained (no CDN, no build step) and also serves the generated document at <prefix>/asyncapi.json and <prefix>/asyncapi.yaml.
prefix is the path the handler is mounted at, without a trailing slash (e.g. "/asyncdocs"). Mount it for both the prefix and everything below it:
h := api.DocsHandler("/asyncdocs")
mux.Handle("/asyncdocs/", h) // net/http also redirects "/asyncdocs"
or with gorilla/mux: router.Handle("/asyncdocs", h) and router.PathPrefix("/asyncdocs/").Handler(h).
Like the document handlers, the document is generated on first request, so register all operations before serving.
func (*API) DocsRoute ¶
DocsRoute, JsonRoute and YamlRoute return the configured mount paths (Config.DocsPath, JSONPath, YAMLPath; defaults "/asyncdocs", "/asyncapi.json", "/asyncapi.yaml"). Use them wherever you need the URL, so changing the config is the only edit.
func (*API) DocsRoutes ¶
DocsRoutes returns the routes serving the interactive reference: DocsRoute exactly and below. It loads the document from JsonRoute/YamlRoute, so mount SpecRoutes too (Routes returns both).
func (*API) Document ¶
Document exposes the underlying model (like huma's api.OpenAPI()). Security and "x-" extensions are already applied by the time Register returns — Document reflects the fully-formed operation immediately.
func (*API) Handle ¶
func (a *API) Handle(method string, h Handler, opts ...RouteOption)
Handle registers a raw, undocumented method directly on the Router — for anything that should not appear in the AsyncAPI document. Prefer Register for anything client-facing.
func (*API) JSON ¶
JSON renders the document and, if Config.Validator is set, runs it over the result. Security, extensions and security schemes are already part of a.doc by the time this runs — Register sets them directly on native fields — so there is no patch step here anymore; this is just marshal and, optionally, validate. Field order is whatever Document's own MarshalJSON produces (declared fields in their struct order, then any "x-" extensions sorted after them), so output is still deterministic.
func (*API) JsonDocHandler ¶
func (*API) RouteGroup ¶
func (a *API) RouteGroup(prefix string, mw ...Middleware) *RouteGroup
RouteGroup groups raw, undocumented methods under a prefix — see Router.RouteGroup. For documented operations, use Group instead.
func (*API) Router ¶
Router exposes the underlying dispatcher, for raw/undocumented registration (see Handle and RouteGroup) or anything else Router offers that API does not forward directly.
func (*API) ServeDocs ¶
ServeDocs mounts the document and the interactive reference on m at the configured paths — the one-liner for the common case:
api.ServeDocs(http.DefaultServeMux) // /asyncapi.json, /asyncapi.yaml, /asyncdocs/
func (*API) SpecRoutes ¶
SpecRoutes returns the routes serving the document: JsonRoute and YamlRoute.
func (*API) Use ¶
func (a *API) Use(mw ...Middleware)
Use adds router-level middleware (see Router.Use), applied to every call — documented Register operations included, since they dispatch through the same Router underneath. For middleware that should see the Operation being called (e.g. to read op.Security), use UseMiddleware instead.
func (*API) UseChannelGate ¶
func (a *API) UseChannelGate(g ...ChannelGate)
UseChannelGate adds gates that authorize every client subscribe and publish before the channel's own handlers run; see ChannelGate. Unlike UseMiddleware it may be called at any time.
func (*API) UseMiddleware ¶
func (a *API) UseMiddleware(mw ...OpMiddleware)
UseMiddleware adds middleware applied to every Register'd operation. It must be called before the first Register, otherwise earlier operations would silently miss it.
func (*API) YamlDocHandler ¶
type CallInfo ¶
type CallInfo struct {
Method string
RequestID string
ClientID string
UserID string
Received time.Time
// Client is nil for in-process calls made via Router.Call.
Client *centrifuge.Client
}
CallInfo is attached to the context of every call.
type Channel ¶
type Channel struct {
// ID names this channel in the document (as Operation.OperationID does
// for RPC) and is used to derive its message and operation names.
ID string
// Pattern is the channel address, with optional {name} placeholders.
Pattern string
Summary string
Description string
Tags []string
// Security gates who may subscribe at the scheme level — see
// ChannelHandle.OnSubscribe for authorization beyond that (e.g. "does
// this specific room belong to this specific caller").
Security []map[string][]string
Extensions map[string]any
// PublishExtensions are the "x-" extensions on the operation that
// documents client publishing (see AllowPublish), e.g. the permissions a
// publisher needs. Channel gates see them as ChannelInfo.PublishExtensions.
PublishExtensions map[string]any
}
Channel describes one addressable, real Centrifuge channel — as opposed to the synthetic "rpc.<method>" channels Register creates for RPC methods. Pattern may contain {name} placeholders (e.g. "chat:{roomId}"), matching AsyncAPI's own channel-parameter convention; a placeholder matches one or more characters that are not ':', matching Centrifuge's usual convention of ':' as a namespace separator in channel names.
type ChannelAction ¶
type ChannelAction string
ChannelAction is what a client is attempting on a channel.
const ( ChannelSubscribe ChannelAction = "subscribe" ChannelPublish ChannelAction = "publish" )
type ChannelGate ¶
type ChannelGate func(ctx context.Context, ch *ChannelInfo, action ChannelAction, params Params, info SubscribeInfo) error
ChannelGate authorizes a client's action on a channel before it happens, the channel counterpart of OpMiddleware: it sees the channel's extensions, so a requirement documented there (say "x-permissions") can be enforced in one place instead of in every channel's OnSubscribe. ctx is the connection's context. Returning an error rejects the action; a *fuge.Error or *centrifuge.Error reaches the client as is (e.g. centrifuge.ErrorPermissionDenied). Gates run in registration order, before the channel's own OnSubscribe.
type ChannelHandle ¶
type ChannelHandle[T any] struct { // contains filtered or unexported fields }
ChannelHandle is returned by RegisterChannel: the typed handle used to publish to this channel, gate subscriptions, and (via AllowPublish) accept client-initiated publishes.
func RegisterChannel ¶
func RegisterChannel[T any](api *API, ch Channel) *ChannelHandle[T]
RegisterChannel documents ch as a real (non-RPC) channel with a "send" operation — the server publishing to it — and returns a handle for publishing typed messages of type T. Combine with AllowPublish if clients (including other services acting as ordinary clients) should be able to publish into it directly.
func (*ChannelHandle[T]) OnSubscribe ¶
func (ch *ChannelHandle[T]) OnSubscribe(fn func(ctx context.Context, params Params, info SubscribeInfo) error) *ChannelHandle[T]
OnSubscribe gates who may subscribe to this channel, beyond the coarse Security requirement — e.g. checking that params["userId"] matches the authenticated caller. Returning an error rejects the subscription. Returns ch so it chains at the call site: RegisterChannel(...).OnSubscribe(...).
func (*ChannelHandle[T]) Publish ¶
func (ch *ChannelHandle[T]) Publish(node *centrifuge.Node, params Params, msg T) error
Publish sends msg to the channel identified by params (e.g. {"roomId": "room-42"} for a channel registered as "chat:{roomId}"), via node.Publish. The type used here is exactly the type RegisterChannel documented for this channel — there is no other way to publish to it.
type ChannelInfo ¶
type ChannelInfo struct {
ID string
Pattern string
Security []map[string][]string
// Extensions are Channel.Extensions: they document subscribing, and are
// what a gate reads to authorize ChannelSubscribe.
Extensions map[string]any
// PublishExtensions are Channel.PublishExtensions, for ChannelPublish.
PublishExtensions map[string]any
}
ChannelInfo describes a registered channel to a ChannelGate. It is shared and must not be modified.
type Codec ¶
Codec converts between wire bytes and Go values. Swap it to use msgpack, protobuf, etc. — pass it via Config.Codec.
var JSON Codec = jsonCodec{}
JSON is the default codec. If you swap the codec, also set Config.DefaultContentType so the document stays truthful.
type Components ¶
type Components struct {
Schemas map[string]json.RawMessage `json:"schemas,omitempty"`
Messages map[string]Message `json:"messages,omitempty"`
Parameters map[string]Parameter `json:"parameters,omitempty"`
Servers map[string]Server `json:"servers,omitempty"`
Channels map[string]SpecChannel `json:"channels,omitempty"`
SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
Components holds reusable definitions referenced from elsewhere in the document. Schemas is where SchemaFromType definitions belong; entries are referenced as "#/components/schemas/Name".
func (Components) MarshalJSON ¶
func (c Components) MarshalJSON() ([]byte, error)
func (*Components) UnmarshalJSON ¶
func (c *Components) UnmarshalJSON(data []byte) error
type Config ¶
type Config struct {
*Document
// SecuritySchemes populate components.securitySchemes.
SecuritySchemes map[string]SecurityScheme
// Codec defaults to JSON.
Codec Codec
// ReflectOptions are passed to SchemaFromType, e.g. RequireAll().
ReflectOptions []ReflectOption
// DocsPath, JSONPath and YAMLPath are where ServeDocs/Routes mount the
// interactive reference and the generated document. Empty values default
// to "/asyncdocs", "/asyncapi.json" and "/asyncapi.yaml"; set one and
// everything derived from it (the routes, the UI's spec links) follows.
DocsPath, JSONPath, YAMLPath string
// Validator, when set, is run on the generated JSON document before it is
// served; its error fails API.JSON. Nil (the default) skips validation.
// validate.Bytes (package fuge/validate) checks against the official
// AsyncAPI meta-schema.
Validator func(document []byte) error
// Docs customizes the interactive reference (title, default websocket URL).
// Its SpecURL/SpecYAMLURL are managed by ServeDocs and ignored there.
Docs DocsOptions
}
Config mirrors huma.Config: it embeds the document so cfg.Info, cfg.Servers, cfg.Components... are edited directly.
func DefaultConfig ¶
DefaultConfig returns a Config with JSON as the content type and codec.
type Contact ¶
type Contact struct {
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Email string `json:"email,omitempty"`
}
Contact identifies who to reach about the API.
type DocsOptions ¶
type DocsOptions struct {
// Title is the browser tab title. Defaults to "<info.title> Reference".
Title string
// WebSocketURL pre-fills the connection bar of the "Try it" client, e.g.
// "wss://api.example.com/connection/websocket". When empty the UI derives
// it from the page's own origin and the document's first server pathname.
// A URL the user typed in earlier (kept in their browser) takes precedence.
WebSocketURL string
// SpecURL makes the UI load the AsyncAPI document from this URL instead of
// the copy this handler serves: a path ("/asyncapi.json") or an absolute
// http(s) URL, whose origin is then allowed by the page's CSP (the server
// must permit cross-origin reads, e.g. CORS). The YAML link is derived by
// swapping a ".json" suffix for ".yaml", and hidden when there is none.
// Any other scheme panics at construction, like a bad http.ServeMux pattern.
SpecURL string
// SpecYAMLURL is the YAML counterpart of SpecURL. When empty it is derived
// from SpecURL as described there. Ignored without SpecURL.
SpecYAMLURL string
// ConnectSrc lists extra origins ("https://idp.example.com") the page may
// fetch from. Origins of the security schemes' token and discovery URLs
// and of SpecURL are added automatically; list others here, e.g. the
// authorization/token endpoints an openIdConnect discovery document
// points at when they live on a different host.
ConnectSrc []string
}
DocsOptions customizes API.DocsHandler. The zero value is valid.
type Document ¶
type Document struct {
AsyncAPI string `json:"asyncapi"`
ID string `json:"id,omitempty"`
Info Info `json:"info"`
DefaultContentType string `json:"defaultContentType,omitempty"`
Servers map[string]Server `json:"servers,omitempty"`
Channels map[string]SpecChannel `json:"channels,omitempty"`
Operations map[string]SpecOperation `json:"operations,omitempty"`
Components *Components `json:"components,omitempty"`
// Extensions holds "x-" values on the document root. See [Extensions].
Extensions Extensions `json:"-"`
}
Document is the root of an AsyncAPI document. Build one with NewDocument so the specification version is set correctly.
func NewDocument ¶
NewDocument returns a Document for AsyncAPI 3.1.0 with its required info fields populated.
func (Document) MarshalJSON ¶
func (*Document) UnmarshalJSON ¶
type Error ¶
type Error struct {
Code uint32
Message string
Temporary bool
// contains filtered or unexported fields
}
Error is a client-visible RPC error. Only Code, Message, and Temporary are sent over the wire; the wrapped cause stays server-side (logs only).
func (*Error) Is ¶
Is makes errors.Is(err, ErrNotFound) work for any error with the same code, including copies produced by WithMessage / Wrap.
func (*Error) WithMessage ¶
WithMessage returns a copy with a different client-visible message.
type ErrorMapper ¶
ErrorMapper lets you translate domain errors (pgx.ErrNoRows, your own sentinel errors...) into client-visible errors. Return ok=false to fall through to the default handling.
type Extensions ¶
Extensions holds "x-" specification extensions: implementation-defined values the specification permits on almost every object, alongside that object's own fields (e.g. a channel, an operation, a security scheme).
Keys must start with "x-". MarshalJSON reports an error otherwise, since a malformed key would silently produce a document that fails meta-schema validation (fuge/validate).
func OAuthExtensions ¶
func OAuthExtensions(o OAuthOptions) Extensions
OAuthExtensions returns the "x-fuge-*" extensions for o, ready to assign to SecurityScheme.Extensions. Zero fields are omitted.
type ExternalDocs ¶
type ExternalDocs struct {
Description string `json:"description,omitempty"`
URL string `json:"url"`
}
ExternalDocs points at documentation held outside the document.
type Group ¶
type Group struct {
// contains filtered or unexported fields
}
Group prefixes method names and tags for the operations registered on it. Unlike RouteGroup, the prefix is visible to the documentation.
type Info ¶
type Info struct {
Title string `json:"title"`
Version string `json:"version"`
Description string `json:"description,omitempty"`
TermsOfService string `json:"termsOfService,omitempty"`
Contact *Contact `json:"contact,omitempty"`
License *License `json:"license,omitempty"`
Tags []Tag `json:"tags,omitempty"`
ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
Info carries metadata about the API. Title and Version are required by the specification.
func (Info) MarshalJSON ¶
func (*Info) UnmarshalJSON ¶
type Logger ¶
type Logger interface {
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
Logger is the subset of *slog.Logger the router needs.
type Message ¶
type Message struct {
Ref string `json:"$ref,omitempty"`
Name string `json:"name,omitempty"`
Title string `json:"title,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
ContentType string `json:"contentType,omitempty"`
Headers json.RawMessage `json:"headers,omitempty"`
Payload json.RawMessage `json:"payload,omitempty"`
Examples json.RawMessage `json:"examples,omitempty"`
Tags []Tag `json:"tags,omitempty"`
Bindings json.RawMessage `json:"bindings,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
Message describes one kind of message on a channel. Set Ref alone to reference a message defined under Components; otherwise Payload carries the schema, typically produced by SchemaFromType.
func (Message) MarshalJSON ¶
func (*Message) UnmarshalJSON ¶
type Middleware ¶
Middleware wraps a Handler. Middleware attached first runs first (outermost).
func Logging ¶
func Logging(l Logger) Middleware
Logging logs one line per call with duration and outcome.
func Observe ¶
func Observe(fn func(info CallInfo, d time.Duration, err error)) Middleware
Observe is the hook for metrics/tracing: called after every call.
func RequireUser ¶
func RequireUser() Middleware
RequireUser rejects calls from anonymous connections.
type Mux ¶
Mux is the part of a router ServeDocs needs. *http.ServeMux and chi's routers satisfy it; for routers whose Handle has a different signature (gorilla/mux) loop over API.Routes instead.
type OAuthFlow ¶
type OAuthFlow struct {
AuthorizationURL string `json:"authorizationUrl,omitempty"`
TokenURL string `json:"tokenUrl,omitempty"`
RefreshURL string `json:"refreshUrl,omitempty"`
AvailableScopes map[string]string `json:"availableScopes"`
}
OAuthFlow configures one OAuth2 flow. AuthorizationURL is required for Implicit and AuthorizationCode; TokenURL is required for Password, ClientCredentials and AuthorizationCode. AvailableScopes is always required — pass an empty, non-nil map if the flow grants no scopes, since a nil map marshals as JSON null and fails validation against the specification's meta-schema.
type OAuthFlows ¶
type OAuthFlows struct {
Implicit *OAuthFlow `json:"implicit,omitempty"`
Password *OAuthFlow `json:"password,omitempty"`
ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}
OAuthFlows configures the OAuth2 flows an "oauth2" SecurityScheme supports. At least one flow must be set.
type OAuthOptions ¶
type OAuthOptions struct {
// ClientID is the public client identifier.
ClientID string
// RedirectURI the identity provider sends the user back to. Defaults to
// the docs page itself, which relays the result to the opener.
RedirectURI string
// UsePKCE for the authorization-code flow: "S256" (default), "plain" or "none".
UsePKCE string
// DefaultScopes are pre-selected.
DefaultScopes []string
// TokenName is the field holding the token in the token response
// (default "access_token").
TokenName string
// CredentialsLocation says where client credentials go on token requests:
// "body" (default) or "header" (HTTP Basic).
CredentialsLocation string
// AuthorizeParams are extra query parameters on the authorization request
// (e.g. {"audience": "api", "prompt": "login"}).
AuthorizeParams map[string]string
// TokenParams are extra form fields on the token request.
TokenParams map[string]string
}
OAuthOptions are the defaults the docs UI pre-fills for an oauth2 or openIdConnect scheme. Every field is optional, and the person using the UI can change any of them before authorizing.
type OpMiddleware ¶
OpMiddleware wraps an OpHandler and can inspect the operation being called, which is what lets a security middleware read op.Security or op.Extensions.
type Operation ¶
type Operation struct {
// OperationID is the stable identifier in the document. Defaults to Method.
OperationID string
// Method is the wire name the client passes to client.rpc(). Required.
Method string
Summary string
Description string
Tags []string
// Security lists acceptable schemes, drop-in compatible with huma's type:
// each map is one alternative (OR). A map holding more than one scheme
// (AND) cannot be expressed in AsyncAPI 3 and panics at registration.
// Scopes are ignored: AsyncAPI 3 carries them on the scheme itself.
Security []map[string][]string
// Errors are extra Centrifuge error codes this method may return. Internal
// error (100) is always documented; bad request (107) is added when the
// request has a payload and validation (422) when it implements Validator.
Errors []uint32
// Extensions are "x-" keys added to the AsyncAPI operation.
Extensions map[string]any
// Timeout overrides the router default for this method.
Timeout time.Duration
}
Operation describes one RPC method. It mirrors huma.Operation: the fields below are what developers fill in; Register translates them into AsyncAPI.
type OperationReply ¶
type OperationReply struct {
Channel RefObj `json:"channel,omitzero"`
Messages []RefObj `json:"messages,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
OperationReply describes the response half of a request/reply exchange, and the channel it arrives on — which may be the request channel itself.
func (OperationReply) MarshalJSON ¶
func (r OperationReply) MarshalJSON() ([]byte, error)
func (*OperationReply) UnmarshalJSON ¶
func (r *OperationReply) UnmarshalJSON(data []byte) error
type Option ¶
type Option func(*config)
func WithDefaultTimeout ¶
WithDefaultTimeout applies a deadline to every route (override per route with WithTimeout). Zero means no deadline.
func WithErrorMapper ¶
func WithErrorMapper(m ErrorMapper) Option
func WithLogger ¶
func WithMaxInflight ¶
WithMaxInflight bounds concurrently running handlers across the router. Excess calls are rejected immediately with ErrorLimitExceeded.
type Parameter ¶
type Parameter struct {
Description string `json:"description,omitempty"`
Enum []string `json:"enum,omitempty"`
Default string `json:"default,omitempty"`
Examples []string `json:"examples,omitempty"`
Location string `json:"location,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
Parameter describes one substitution in a channel address.
func (Parameter) MarshalJSON ¶
func (*Parameter) UnmarshalJSON ¶
type Params ¶
Params holds the values extracted from a channel address's parameters — e.g. {"roomId": "room-42"} for a channel registered with pattern "chat:{roomId}" when a client subscribes to "chat:room-42".
type RefObj ¶
type RefObj struct {
Ref string `json:"$ref,omitempty"`
}
RefObj is a JSON Reference to another part of the document. Build one with Ref.
type ReflectOption ¶
type ReflectOption func(*reflectConfig)
ReflectOption configures SchemaFromType.
func RequireAll ¶
func RequireAll() ReflectOption
RequireAll marks every property of every reflected definition as required. Correct only for payloads whose Go structs never use omitempty — Go then marshals every field on every message.
type Registrar ¶
type Registrar interface {
// contains filtered or unexported methods
}
Registrar is implemented by *API and *Group so Register works on both.
type Route ¶
Route is one path to mount. Subtree means "this path and everything below it" (a prefix match); otherwise it is an exact match.
type RouteGroup ¶
type RouteGroup struct {
// contains filtered or unexported fields
}
func (*RouteGroup) Handle ¶
func (g *RouteGroup) Handle(method string, h Handler, opts ...RouteOption)
func (*RouteGroup) RouteGroup ¶
func (g *RouteGroup) RouteGroup(prefix string, mw ...Middleware) *RouteGroup
RouteGroup creates a sub-group; names become "<parent>.<prefix>.<method>".
func (*RouteGroup) Use ¶
func (g *RouteGroup) Use(mw ...Middleware)
type RouteOption ¶
type RouteOption func(*routeConfig)
func WithMiddleware ¶
func WithMiddleware(mw ...Middleware) RouteOption
WithMiddleware adds middleware that applies to this route only, innermost.
func WithTimeout ¶
func WithTimeout(d time.Duration) RouteOption
WithTimeout overrides the default timeout for one route (0 disables it).
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
func (*Router) Attach ¶
func (r *Router) Attach(c *centrifuge.Client)
Attach wires the router into a client. Call it from node.OnConnect:
node.OnConnect(func(c *centrifuge.Client) { router.Attach(c) })
func (*Router) Call ¶
Call runs a route in-process without Centrifuge: ideal for unit tests. Returned errors are the raw handler errors (not mapped to wire errors).
func (*Router) RouteGroup ¶
func (r *Router) RouteGroup(prefix string, mw ...Middleware) *RouteGroup
func (*Router) Use ¶
func (r *Router) Use(mw ...Middleware)
Use adds router-wide middleware. Order of Use vs Handle calls does not matter: the final chain is built once, when the router is first used.
type SecurityScheme ¶
type SecurityScheme struct {
Type string `json:"type"`
Description string `json:"description,omitempty"`
Name string `json:"name,omitempty"`
In string `json:"in,omitempty"`
Scheme string `json:"scheme,omitempty"`
BearerFormat string `json:"bearerFormat,omitempty"`
Flows *OAuthFlows `json:"flows,omitempty"`
OpenIDConnectURL string `json:"openIdConnectUrl,omitempty"`
Scopes []string `json:"scopes,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
SecurityScheme defines an authentication or authorization mechanism that operations can require. Define schemes under Components.SecuritySchemes and reference them from SpecOperation.Security with Ref("#/components/securitySchemes/<name>") — AsyncAPI's operation security list is a flat "OR" of scheme references (any one satisfies the operation), unlike OpenAPI's map-of-scheme-to-scopes; there is no way to require two schemes at once (an "AND"), and this package does not model an inline (non-referenced) SecurityScheme literal in that list.
fuge supports only the token-based schemes a browser WebSocket can carry, and New panics on any other Type:
http — Scheme must be "bearer"; BearerFormat optional ("JWT")
httpApiKey — Name, In: "query" or "cookie" (not "header": browsers cannot
set headers on a WebSocket)
oauth2 — Flows (any of the four), and optionally Scopes
openIdConnect — OpenIDConnectURL (the .well-known/openid-configuration URL)
For oauth2 and openIdConnect, the interactive docs UI can run the flows and pre-fills them from the scheme; tune that with OAuthExtensions ("x-fuge-*" keys on Extensions). the meta-schema (see fuge/validate) catches combinations the specification itself doesn't allow.
func (SecurityScheme) MarshalJSON ¶
func (s SecurityScheme) MarshalJSON() ([]byte, error)
func (*SecurityScheme) UnmarshalJSON ¶
func (s *SecurityScheme) UnmarshalJSON(data []byte) error
type Server ¶
type Server struct {
Host string `json:"host"`
Protocol string `json:"protocol"`
Pathname string `json:"pathname,omitempty"`
Description string `json:"description,omitempty"`
Title string `json:"title,omitempty"`
Summary string `json:"summary,omitempty"`
Tags []Tag `json:"tags,omitempty"`
Bindings json.RawMessage `json:"bindings,omitempty"`
Security []RefObj `json:"security,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
Server describes where the API is reachable. Host and Protocol are required by the specification; Bindings carries protocol-specific configuration as raw JSON.
func (Server) MarshalJSON ¶
func (*Server) UnmarshalJSON ¶
type SpecChannel ¶
type SpecChannel struct {
Address string `json:"address,omitempty"`
Title string `json:"title,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Messages map[string]Message `json:"messages,omitempty"`
Parameters map[string]Parameter `json:"parameters,omitempty"`
Servers []RefObj `json:"servers,omitempty"`
Tags []Tag `json:"tags,omitempty"`
Bindings json.RawMessage `json:"bindings,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
SpecChannel is an addressable path messages flow through. An Address may embed parameters in braces — "/ports/{unlocode}" — each of which must have a matching entry in Parameters.
func (SpecChannel) MarshalJSON ¶
func (c SpecChannel) MarshalJSON() ([]byte, error)
func (*SpecChannel) UnmarshalJSON ¶
func (c *SpecChannel) UnmarshalJSON(data []byte) error
type SpecOperation ¶
type SpecOperation struct {
Action string `json:"action,omitempty"`
Channel RefObj `json:"channel,omitzero"`
Title string `json:"title,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Messages []RefObj `json:"messages,omitempty"`
Reply *OperationReply `json:"reply,omitempty"`
// Security lists acceptable security schemes as references into
// Components.SecuritySchemes, e.g. Ref("#/components/securitySchemes/bearer").
// Any one entry satisfies the operation (a logical OR); see [SecurityScheme].
Security []RefObj `json:"security,omitempty"`
Tags []Tag `json:"tags,omitempty"`
Bindings json.RawMessage `json:"bindings,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
SpecOperation is an action the application performs on a channel: ActionSend or ActionReceive. Set Reply to describe a request/reply exchange.
func (SpecOperation) MarshalJSON ¶
func (o SpecOperation) MarshalJSON() ([]byte, error)
func (*SpecOperation) UnmarshalJSON ¶
func (o *SpecOperation) UnmarshalJSON(data []byte) error
type SubscribeInfo ¶
type SubscribeInfo struct {
UserID string
ClientID string
Channel string // the literal address requested, e.g. "chat:room-42"
}
SubscribeInfo is what a channel's OnSubscribe handler receives about the client attempting to subscribe.
type Tag ¶
type Tag struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
// Extensions holds "x-" values on this object. See [Extensions].
Extensions Extensions `json:"-"`
}
Tag groups channels, operations, or messages under a common label.
func (Tag) MarshalJSON ¶
func (*Tag) UnmarshalJSON ¶
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Command example is a minimal, runnable demonstration of fuge: it builds an API, registers one documented RPC method, wires it into both Centrifuge and HTTP, and prints the generated AsyncAPI document.
|
Command example is a minimal, runnable demonstration of fuge: it builds an API, registers one documented RPC method, wires it into both Centrifuge and HTTP, and prints the generated AsyncAPI document. |
|
showcase
command
Command showcase runs a small live fuge server: a few documented RPC methods and a channel behind a real Centrifuge node, with the interactive reference mounted so you can click through it and use "Try it".
|
Command showcase runs a small live fuge server: a few documented RPC methods and a channel behind a real Centrifuge node, with the interactive reference mounted so you can click through it and use "Try it". |
|
Package validate checks a generated AsyncAPI 3.1.0 document against the official meta-schema.
|
Package validate checks a generated AsyncAPI 3.1.0 document against the official meta-schema. |



