Documentation
¶
Overview ¶
Package apiframework provides HTTP request/response helpers for the Contenox API.
For OpenAPI generation (tools/openapi-gen), place // @request pkg.Type after Decode and // @response pkg.Type after Encode, on the line of the call's closing paren. Parameters are derived from the helper calls in the handler's own body: GetQueryParam carries the query parameter's name, default and description; GetPathParam attaches its description to the route template's path parameter.
ListParams, CursorParam and LimitParam are INVISIBLE to the generator and always will be: their GetQueryParam calls are inside this package rather than the handler's body, and they pass a constant description rather than a literal. A handler that pages through them documents the // @param name type description directive in its doc comment instead — the escape hatch for every parameter a helper hides (a helper-derived parameter of the same name wins, being read from the handler itself).
// @security, // @response-header and // @sse-response are likewise doc-comment directives. See docs/api-conventions.md for the whole contract; every rule there states what breaks when it is missed.
The package is deliberately standalone: it imports nothing from the runtime module. The serverops: prefix on the error strings predates the package's rename and is left as-is, because callers match on those strings.
Index ¶
- Constants
- Variables
- func CursorParam(r *http.Request) (*time.Time, error)
- func Decode[T any](r *http.Request) (T, error)
- func Encode[T any](w http.ResponseWriter, _ *http.Request, status int, v T) error
- func EnforceToken(expectedToken string, next http.Handler) http.Handler
- func Error(w http.ResponseWriter, r *http.Request, err error, op Operation) error
- func GetErrorParam(err error) string
- func GetPathParam(r *http.Request, name string, description string) string
- func GetQueryParam(r *http.Request, name, defaultValue, description string) string
- func HandleAPIError(resp *http.Response) error
- func IsAPIError(err error) (message, errorCode, errorType, param string, ok bool)
- func LimitParam(r *http.Request, defaultLimit int) (int, error)
- func ListParams(r *http.Request, defaultLimit int) (*time.Time, int, error)
- func RequestIDMiddleware(next http.Handler) http.Handler
- func TokenMiddleware(next http.Handler) http.Handler
- func TracingMiddleware(next http.Handler) http.Handler
- type APIError
- func BadPathValue(param string, message ...string) *APIError
- func BadRequest(message ...string) *APIError
- func Conflict(message ...string) *APIError
- func FileEmpty(message ...string) *APIError
- func FileSizeLimitExceeded(message ...string) *APIError
- func Forbidden(message ...string) *APIError
- func ImmutableGroup(message ...string) *APIError
- func ImmutableModel(message ...string) *APIError
- func InternalServerError(message ...string) *APIError
- func InvalidChain(message ...string) *APIError
- func InvalidParameterValue(param string, message ...string) *APIError
- func MissingParameter(param string, message ...string) *APIError
- func NewAPIError(err error, message, param string) *APIError
- func NotFound(message ...string) *APIError
- func ServiceUnavailable(message ...string) *APIError
- func TooManyRequests(message ...string) *APIError
- func Unauthorized(message ...string) *APIError
- func UnprocessableEntity(message ...string) *APIError
- func UnsupportedMediaType(message ...string) *APIError
- type AboutServer
- type ContextKey
- type MessageResponse
- type Operation
Constants ¶
const ( CursorParamDescription = "An optional RFC3339Nano timestamp to fetch the next page of results." LimitParamDescription = "The maximum number of items to return per page." )
CursorParamDescription and LimitParamDescription are the canonical documentation for the two shared pagination query parameters.
They reach a client only if a handler repeats them: the generator reads GetQueryParam calls in the HANDLER's body with LITERAL arguments, and the calls below are in this file and pass these constants. A paginated route documents its two parameters with `// @param cursor string …` and `// @param limit integer …` in the handler's doc comment, or by calling GetQueryParam directly with literals.
Variables ¶
var ( ErrEncodeInvalidJSON = errors.New("serverops: encoding failing, invalid json") ErrDecodeInvalidJSON = errors.New("serverops: decoding failing, invalid json") ErrDecodeInvalidYAML = errors.New("serverops: decoding failing, invalid yaml") ErrDecodeBase64 = errors.New("serverops: decoding failing, invalid base64 data") ErrUnsupportedContentType = errors.New("serverops: unsupported content type for decoding") ErrReadingRequestBody = errors.New("serverops: failed to read request body") ErrMalformedContentType = errors.New("serverops: malformed Content-Type header") )
var ( ErrInvalidParameterValue = errors.New("serverops: invalid parameter value type") ErrBadPathValue = errors.New("serverops: bad path value") ErrBadQueryValue = errors.New("serverops: bad query value") ErrImmutableModel = errors.New("serverops: immutable model") ErrImmutableGroup = errors.New("serverops: immutable group") ErrMissingParameter = errors.New("serverops: missing parameter") ErrEmptyRequest = errors.New("serverops: empty request") ErrEmptyRequestBody = errors.New("serverops: empty request body") ErrInvalidChain = errors.New("serverops: invalid chain definition") ErrBadRequest = errors.New("serverops: bad request") ErrUnprocessableEntity = errors.New("serverops: unprocessable entity") ErrNotFound = errors.New("serverops: not found") ErrConflict = errors.New("serverops: conflict") ErrForbidden = errors.New("serverops: forbidden") ErrInternalServerError = errors.New("serverops: internal server error") ErrUnsupportedMediaType = errors.New("serverops: unsupported media type") ErrFileSizeLimitExceeded = errors.New("serverops: file size limit exceeded") ErrFileEmpty = errors.New("serverops: file cannot be empty") // ErrTooManyRequests is a caller refused for rate rather than for // content. Distinct from ErrConflict because a 429 says "later" and a // 409 says "no": only one of them is worth retrying. ErrTooManyRequests = errors.New("serverops: too many requests") )
var ( ContextKeyRequestID = libtracker.ContextKeyRequestID ContextKeyTraceID = libtracker.ContextKeyTraceID ContextKeySpanID = libtracker.ContextKeySpanID )
ContextKeyRequestID, ContextKeyTraceID and ContextKeySpanID are re-exported so callers in this module have one import for the middleware and the keys.
Functions ¶
func CursorParam ¶ added in v1.1.0
CursorParam parses the optional RFC3339Nano `cursor` query parameter. An absent (or empty) cursor yields a nil pointer and no error; a malformed one yields ErrInvalidParameterValue.
func Error ¶
Error writes an OpenAI-compatible error response for err, choosing the HTTP status from the operation and the error's identity. Components the error does not carry fall back to a status-derived mapping, and param is emitted as null when empty, which is the OpenAI convention.
func GetErrorParam ¶
GetErrorParam extracts the parameter from err when it carries one.
func GetPathParam ¶
GetPathParam retrieves a URL path parameter by name. The call is also the documentation source: the OpenAPI generator (tools/openapi-gen) derives the path parameter itself from the route template, and attaches the description argument of a GetPathParam call found in the handler's own body to it. name and description must both be string literals; a non-literal argument is consumed as absent and the parameter is documented without a description.
Naming a parameter that appears in no route template bound to the handler is silently dropped rather than reported. The description is also attached to the PATH rather than the operation, and only the first handler on a shared templated path is read, so every handler on one path should call GetPathParam with the same description.
The call must be in the handler's own body. Moving it into a shared helper still routes correctly and documents an undescribed parameter.
func GetQueryParam ¶
GetQueryParam retrieves a URL query parameter by name. If the parameter is not present, it returns the provided defaultValue.
The call is also the documentation source: the OpenAPI generator emits a string query parameter for every GetQueryParam call in the handler's own body, carrying this description and — when the defaultValue literal is non-empty — a schema default. name must be a string literal (a non-literal name fails generation); a non-literal defaultValue or description is consumed as absent. All four arguments must be present; a call with any other arity is not matched. Calls the generator cannot see (nested closures, shared helpers called from the handler, including ListParams and friends below) are documented with the `// @param name type description` directive in the handler's DOC COMMENT instead.
func HandleAPIError ¶
HandleAPIError processes OpenAI-compatible API error responses.
func IsAPIError ¶
IsAPIError reports whether err is an *APIError and returns its components.
func LimitParam ¶ added in v1.1.0
LimitParam parses the optional integer `limit` query parameter, returning defaultLimit when it is absent. An unparseable limit, or one below 1, yields ErrInvalidParameterValue; defaultLimit is trusted and returned unchecked, so a call site that wants "let the store decide" can still pass 0 or a negative value of its own.
func ListParams ¶ added in v1.1.0
ListParams parses the two pagination query parameters shared by every keyset-paginated list endpoint: an optional RFC3339Nano `cursor` and an optional integer `limit`.
Absent and invalid are deliberately different answers:
- absent cursor -> nil cursor, no error (start at the newest page)
- absent limit -> defaultLimit, no error (the call site's own default, which several stores in turn read as "apply my own default")
- malformed cursor, unparseable limit, or limit < 1 -> a classified ErrInvalidParameterValue naming the offending parameter, which mapErrorToStatus turns into 400 Bad Request regardless of the Operation the handler passes to Error.
The last point is why this lives here rather than in each handler: a bare fmt.Errorf parse error is unclassified, and the ListOperation fallback in mapErrorToStatus renders unclassified errors as 404 — so a garbage cursor used to read as "no such collection" on some routes and 422 on others.
defaultLimit is a parameter rather than a package constant so call sites keep owning their own default. The cursor is validated before the limit, so a request that gets both wrong is told about the cursor first.
func RequestIDMiddleware ¶
RequestIDMiddleware stamps an inbound X-Request-ID, or mints one, and echoes it on the response.
It has to be MOUNTED to do anything; it was written and never wired, so no host response has ever carried the header.
Types ¶
type APIError ¶
type APIError struct {
// contains filtered or unexported fields
}
APIError wraps an error with parameter context for API responses.
func BadPathValue ¶
func BadRequest ¶
func FileSizeLimitExceeded ¶
func ImmutableGroup ¶
func ImmutableModel ¶
func InternalServerError ¶
func InvalidChain ¶
func InvalidParameterValue ¶
func MissingParameter ¶
func NewAPIError ¶
func ServiceUnavailable ¶ added in v1.1.0
func TooManyRequests ¶ added in v1.1.0
func Unauthorized ¶
func UnprocessableEntity ¶
func UnsupportedMediaType ¶
func (*APIError) WithCode ¶ added in v1.1.0
WithCode returns a copy of e whose machine-readable envelope code is code, leaving status, type, message and param as they were. It exists for the refusals a client maps by code — the seat and entitlement walls — where the sentinel-derived code would say only "conflict" or "forbidden".
type AboutServer ¶
type MessageResponse ¶ added in v0.6.6
type MessageResponse struct {
Message string `json:"message"`
}
MessageResponse is the preferred success body for simple endpoints that only need to return a human-readable message without introducing a route-specific DTO shape.
Route handlers should still use Encode and annotate the call with:
// @response apiframework.MessageResponse