Skip to content

contract — API Quick Reference

This page lists every public symbol exported by github.com/spcent/plumego/contract. Use it as a lookup when you already know the package; use the Contract Primer when you need the boundary rationale and usage patterns.

import "github.com/spcent/plumego/contract"

func WriteResponse(w http.ResponseWriter, r *http.Request, status int, data any, meta any) error

Writes a JSON success response. data is placed in the "data" key; meta (if non-nil) is placed in the "meta" key. Sets Content-Type: application/json and injects request_id from context when the requestid middleware has run.

Wire format:

{
"data": { /* data */ },
"meta": { /* meta, omitted when nil */ },
"request_id": "abc-123"
}
func WriteError(w http.ResponseWriter, r *http.Request, err *APIError) error

Writes a JSON error response using the envelope defined by APIError. The HTTP status code is taken from err.Status. Injects request_id when available.

Wire format:

{
"error": {
"type": "not_found",
"code": "NOT_FOUND",
"message": "user not found",
"category": "resource_error",
"severity": "error",
"details": {}
},
"request_id": "abc-123"
}

func NewErrorBuilder() *ErrorBuilder

Creates a new ErrorBuilder. Chain methods, then call Build().

MethodSignatureEffect
Type(et ErrorType) *ErrorBuilderSets type, code, HTTP status, category, and severity from the catalog
Message(msg string) *ErrorBuilderOverrides the human-readable error message
Detail(key, value string) *ErrorBuilderAdds a key-value pair to the details map
Build() *APIErrorReturns the completed *APIError

type APIError struct {
Type string
Code string
Message string
Category string
Severity string
Details map[string]string
Status int
}

Do not construct APIError as a struct literal. Use NewErrorBuilder().Type(...).Build().


ErrorType is a string constant. Passing it to .Type(et) on the builder sets type, code, category, HTTP status, and default message automatically.

ConstantHTTP statustype valueUse when
TypeRequired400required_field_missingRequired param or body field is absent
TypeValidation400validation_errorField present but fails validation
TypeInvalidFormat400invalid_formatFormat wrong (UUID, email, date, etc.)
TypeInvalidJSON400invalid_jsonRequest body is not valid JSON
TypeOutOfRange400out_of_rangeValue outside allowed range
TypeDuplicate400duplicate_valueValue already exists
TypeUnauthorized401unauthorizedRequest is not authenticated
TypeInvalidToken401invalid_tokenToken is malformed or has an invalid signature
TypeExpiredToken401expired_tokenToken has expired
TypeForbidden403forbiddenAuthenticated but lacks permission
TypeNotFound404not_foundResource not found
TypeConflict409conflictState conflict (e.g. concurrent update)
TypeAlreadyExists409already_existsResource already exists
TypeGone410goneResource permanently deleted
TypeRateLimited429rate_limitedRate limit exceeded
TypeInternal500internal_errorServer-side failure
TypeUnavailable503service_unavailableDownstream dependency unavailable
TypeTimeout504timeoutUpstream call timed out

func RequestIDFromContext(ctx context.Context) string

Returns the request ID injected by middleware/requestid. Returns "" when the middleware has not run.

func RequestContextFromContext(ctx context.Context) RequestContext

Returns the RequestContext set by the router after route matching.

type RequestContext struct {
Params map[string]string
RoutePattern string
RouteName string
}
FieldValue
ParamsMap of path parameter names to values (e.g. {"id": "42"})
RoutePatternThe registered pattern that matched (e.g. /api/users/:id)
RouteNameThe name set with router.WithRouteName, or ""

func MustParam(r *http.Request, key string) string

Returns RequestContext.Params[key]. Panics when the param is not present. Use only when the route registration guarantees the param exists.

func Param(r *http.Request, key string) (string, bool)

Returns (value, true) when the param is present, ("", false) when absent.