apiframework

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 1, 2026 License: Apache-2.0 Imports: 16 Imported by: 0

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

View Source
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

View Source
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")
)
View Source
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")
	ErrUnauthorized          = errors.New("serverops: unauthorized")
	ErrFileSizeLimitExceeded = errors.New("serverops: file size limit exceeded")
	ErrFileEmpty             = errors.New("serverops: file cannot be empty")
	ErrServiceUnavailable    = errors.New("serverops: service unavailable")
	// 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")
)
View Source
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

func CursorParam(r *http.Request) (*time.Time, error)

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 Decode

func Decode[T any](r *http.Request) (T, error)

func Encode

func Encode[T any](w http.ResponseWriter, _ *http.Request, status int, v T) error

func EnforceToken

func EnforceToken(expectedToken string, next http.Handler) http.Handler

func Error

func Error(w http.ResponseWriter, r *http.Request, err error, op Operation) 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

func GetErrorParam(err error) string

GetErrorParam extracts the parameter from err when it carries one.

func GetPathParam

func GetPathParam(r *http.Request, name string, description string) string

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

func GetQueryParam(r *http.Request, name, defaultValue, description string) string

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

func HandleAPIError(resp *http.Response) error

HandleAPIError processes OpenAI-compatible API error responses.

func IsAPIError

func IsAPIError(err error) (message, errorCode, errorType, param string, ok bool)

IsAPIError reports whether err is an *APIError and returns its components.

func LimitParam added in v1.1.0

func LimitParam(r *http.Request, defaultLimit int) (int, error)

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

func ListParams(r *http.Request, defaultLimit int) (*time.Time, int, error)

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

func RequestIDMiddleware(next http.Handler) http.Handler

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.

func TokenMiddleware

func TokenMiddleware(next http.Handler) http.Handler

func TracingMiddleware

func TracingMiddleware(next http.Handler) http.Handler

TracingMiddleware extracts trace and span IDs from an inbound W3C traceparent header, or mints them. A minted span ID is 16 hex characters, so the UUID's dashes are stripped before truncating.

Types

type APIError

type APIError struct {
	// contains filtered or unexported fields
}

APIError wraps an error with parameter context for API responses.

func BadPathValue

func BadPathValue(param string, message ...string) *APIError

func BadRequest

func BadRequest(message ...string) *APIError

func Conflict

func Conflict(message ...string) *APIError

func FileEmpty

func FileEmpty(message ...string) *APIError

func FileSizeLimitExceeded

func FileSizeLimitExceeded(message ...string) *APIError

func Forbidden

func Forbidden(message ...string) *APIError

func ImmutableGroup

func ImmutableGroup(message ...string) *APIError

func ImmutableModel

func ImmutableModel(message ...string) *APIError

func InternalServerError

func InternalServerError(message ...string) *APIError

func InvalidChain

func InvalidChain(message ...string) *APIError

func InvalidParameterValue

func InvalidParameterValue(param string, message ...string) *APIError

func MissingParameter

func MissingParameter(param string, message ...string) *APIError

func NewAPIError

func NewAPIError(err error, message, param string) *APIError

func NotFound

func NotFound(message ...string) *APIError

func ServiceUnavailable added in v1.1.0

func ServiceUnavailable(message ...string) *APIError

func TooManyRequests added in v1.1.0

func TooManyRequests(message ...string) *APIError

func Unauthorized

func Unauthorized(message ...string) *APIError

func UnprocessableEntity

func UnprocessableEntity(message ...string) *APIError

func UnsupportedMediaType

func UnsupportedMediaType(message ...string) *APIError

func (*APIError) Code

func (e *APIError) Code() string

Code returns the error code.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

func (*APIError) Param

func (e *APIError) Param() string

Param returns the parameter associated with the error.

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the underlying error.

func (*APIError) WithCode added in v1.1.0

func (e *APIError) WithCode(code string) *APIError

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 AboutServer struct {
	Version        string `json:"version"`
	NodeInstanceID string `json:"nodeInstanceID"`
	Tenancy        string `json:"tenancy"`
}

type ContextKey

type ContextKey string
const (
	ContextTokenKey ContextKey = "token"
)

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

type Operation

type Operation uint16
const (
	CreateOperation Operation = iota
	GetOperation
	UpdateOperation
	DeleteOperation
	ListOperation
	AuthorizeOperation
	ServerOperation
	ExecuteOperation
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL