Documentation
¶
Overview ¶
Package response provides the canonical fleet HTTP response envelope.
Every fleet JSON response wraps its payload in a consistent shape:
{"status":"success", "data":{...}, "_emitted_at":"...", "_schema_version":N}
{"status":"error", "error":{"code":403,"error_code":"auth.forbidden","message":"..."}}
Use Success(data), NewError(status, code, msg), or ErrorResp(status, msg). The Envelope function merges fleet metadata fields into any JSON payload.
envelope.go adds the fleet-wide schema-version envelope helper.
Why this exists: when a service renames a JSON field, removes one, or changes its semantics, downstream consumers break silently — they keep reading a key that no longer exists or, worse, reads a field whose meaning quietly changed. A monotonically increasing integer carried on every envelope lets consumers (catalog, hub, audit-graph, sibling services) pin a version, refuse unexpected drift, and surface incompatibilities in CI rather than at runtime.
The integer is set per service via server.WithSchemaVersion(N) and is exposed at GET /schema and inside GET /capabilities. Handlers stamp it onto every response by wrapping the payload:
response.Envelope(payload, server.CurrentSchemaVersion())
See response/SCHEMA_VERSIONING.md for when to bump and the fleet-wide migration recipe.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DecodeData ¶
DecodeData reads a fleet response envelope from r and unmarshals its "data" object into v.
The fleet envelope (see Success / NewError) is:
{"status":"success","data":{...}} // success
{"status":"error","error":{"code":...}} // failure
Consumers that hand-rolled a *top-level* decode (e.g. a bare struct{ Value string `json:"value"` }) silently missed the nested data object and read zero values instead. That exact mismatch broke the go-fleet-dns-sync reconciler for 10 days in 2026-05 — it decoded the vault's secret at the top level while the value lived under "data". DecodeData defines the contract once so it can't drift per-consumer.
Behaviour:
- status == "error" (or an error object is present): returns the decoded *Error (which implements error) so callers can switch on Code / ErrorCode.
- status == "success" with data: json.Unmarshal(data, v). Pass v == nil to validate the envelope without unmarshalling.
- success but data absent/null while v != nil: returns an error (an empty data object is almost always a producer bug the caller wants surfaced rather than a silent zero value).
DecodeData never includes the raw body in its returned errors, so a decode failure on a secret-bearing response will not leak the secret.
func DecodeDataBytes ¶
DecodeDataBytes is the []byte convenience wrapper around DecodeData.
func Envelope ¶
Envelope wraps an arbitrary payload in the fleet schema envelope.
The returned map always contains:
- _schema_version: the integer passed in (omitted when 0)
- _service: the service identity registered by server.New (omitted when unset or when the payload already defines _service — see conflict rule below)
- _emitted_at: RFC3339Nano UTC timestamp
plus every top-level field of data:
- data == nil: just the envelope keys
- data is map[string]any: keys merged in (envelope wins on its own meta keys unless data conflicts)
- data is a struct/other: marshalled to JSON, unmarshalled into a map, then merged. Non-object JSON (e.g. a bare array or string) is placed under the "data" key.
Conflict rule: if the user payload already carries one of the reserved meta keys (_schema_version, _service, _emitted_at) we log a warning to stderr and prefer the user's value. These are debug-time problems, not crashes — silently dropping a caller's field would be worse than the warning.
func SetDefaultObserver ¶
func SetDefaultObserver(o Observer)
SetDefaultObserver installs a process-wide envelope observer. Pass nil to disable. Wired by promx.AutoWire when present so every Envelope call in the process produces metrics.
func SetServiceID ¶
func SetServiceID(id string)
SetServiceID is called by server.New to publish the running service's identity to the response package. Idempotent.
Types ¶
type Error ¶
type Error struct {
// Code is the HTTP status code (403, 404, 500, …).
Code int `json:"code"`
// ErrorCode is a stable, dotted, machine-readable identifier,
// e.g. "auth.scope_mismatch", "not_found", "bad_request.validation".
// Clients should switch on this field, not on Message.
ErrorCode string `json:"error_code,omitempty"`
// Message is a human-readable description safe to surface in responses.
Message string `json:"message"`
}
Error is the error sub-object in a Response. It carries both an HTTP status code and a stable machine-readable error_code so clients can switch on Code without parsing the human-readable Message.
JSON shape:
{
"status": "error",
"error": {
"code": 403,
"error_code": "auth.scope_mismatch",
"message": "token scope does not cover this resource"
}
}
type Event ¶
Event is the per-Envelope payload handed to an Observer.
Warning is non-empty when the payload carried a reserved meta key (_service, _schema_version, _emitted_at) that conflicted with the envelope's own — the existing stderr log line is kept, this just makes it countable. SchemaVersion is the integer the caller passed (0 when omitted).
type Observer ¶
type Observer interface {
ObserveEnvelope(Event)
}
Observer receives one event per Envelope() call. Implementations MUST NOT block — callbacks run inline on the response hot path. The canonical implementation lives in go-common/promx and records Prometheus counters for envelope emission and conflict warnings.
response deliberately defines the contract here rather than importing a metrics library: response keeps zero metric-stack deps.
func DefaultObserver ¶
func DefaultObserver() Observer
DefaultObserver returns the current process-wide observer or nil.
type Response ¶
type Response struct {
Status string `json:"status"` // "success" or "error"
Data interface{} `json:"data,omitempty"`
Error *Error `json:"error,omitempty"`
Meta interface{} `json:"meta,omitempty"`
}
Response is the canonical fleet API response envelope. All fleet HTTP handlers should return their data through this shape.
func ErrorResp ¶
ErrorResp creates an error Response with only an HTTP status code and message. Prefer NewError when you have a stable error_code.
func FromError ¶
FromError creates an error Response from a standard error value. If err is nil, Success(nil) is returned. If err carries an *errors.Error (from go-common/errors) the HTTP status and error_code are used directly. Otherwise a synthetic 500 internal error is returned.
Note: importing go-common/errors here would create an import cycle since errors/ is a leaf package. Callers that use go-common/errors should use NewError directly.
func NewError ¶
NewError creates an error Response with a machine-readable error_code. This is the canonical constructor for all fleet API error responses.
response.NewError(http.StatusForbidden, "auth.scope_mismatch",
"token scope does not cover this resource")
Example ¶
Every fleet endpoint answers in this envelope; errors carry a stable error_code next to the HTTP status.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/baditaflorin/go-common/response"
)
func main() {
body, _ := json.Marshal(response.NewError(http.StatusForbidden,
"auth.scope_mismatch", "token scope does not cover this resource"))
fmt.Println(string(body))
}
Output: {"status":"error","error":{"code":403,"error_code":"auth.scope_mismatch","message":"token scope does not cover this resource"}}
func Success ¶
func Success(data interface{}) Response
Success wraps data in a successful Response envelope.
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/baditaflorin/go-common/response"
)
func main() {
body, _ := json.Marshal(response.Success(map[string]int{"count": 2}))
fmt.Println(string(body))
}
Output: {"status":"success","data":{"count":2}}