Documentation
¶
Overview ¶
Package apicontract implements the shared HTTP API contract for Workspace apps.
It parses query strings and JSON request bodies into typed structs, rejects input a route does not declare, writes the list envelope and RFC 9457 problem bodies, signs opaque cursors, and describes the same structs as JSON Schema and OpenAPI so specs and tool schemas match the parser.
Example (DayRange) ¶
package main
import (
"fmt"
"net/http/httptest"
"time"
"github.com/whilesmartgo/apicontract"
)
func main() {
var q struct {
apicontract.Range
apicontract.Zone
}
request := httptest.NewRequest("GET", "/events?from=2026-11-14&to=2026-11-14&tz=Europe/Berlin", nil)
if err := apicontract.BindQuery(request, &q); err != nil {
panic(err)
}
fmt.Println(q.From.Format(time.RFC3339))
fmt.Println(q.To.Format(time.RFC3339))
}
Output: 2026-11-14T00:00:00+01:00 2026-11-15T00:00:00+01:00
Example (Paging) ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/whilesmartgo/apicontract"
)
func serve(h http.Handler, method, target, body string) {
request := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request)
show(recorder)
}
func show(recorder *httptest.ResponseRecorder) {
var indented bytes.Buffer
body := bytes.TrimSpace(recorder.Body.Bytes())
if err := json.Indent(&indented, body, "", " "); err != nil {
indented.Write(body)
}
fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}
type note struct {
ID int `json:"id"`
Title string `json:"title"`
}
type notesList struct {
apicontract.Page
apicontract.Search
}
func listNotes(cursors *apicontract.Cursors, all []note) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var q notesList
if err := apicontract.BindQuery(r, &q); err != nil {
_ = apicontract.WriteProblem(w, err)
return
}
binding := apicontract.RequestBinding(r, "user-1")
var after struct {
ID int `json:"id"`
}
if q.Cursor != "" {
if err := cursors.Decode(q.Cursor, binding, &after); err != nil {
_ = apicontract.WriteProblem(w, err)
return
}
}
start := after.ID
end := min(start+q.Limit, len(all))
next := ""
if end < len(all) {
next, _ = cursors.Encode(binding, map[string]int{"id": end})
}
_ = apicontract.WriteList(w, all[start:end], next)
}
}
func main() {
cursors, _ := apicontract.NewCursors([]byte("an example key of at least 32 bytes"))
h := listNotes(cursors, []note{{1, "Budget"}, {2, "Roadmap"}, {3, "Hiring"}})
serve(h, "GET", "/notes?limit=2", "")
serve(h, "GET", "/notes?limit=2&cursor=eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E", "")
serve(h, "GET", "/notes?limit=2&q=budget&cursor=eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E", "")
}
Output: 200 application/json { "items": [ { "id": 1, "title": "Budget" }, { "id": 2, "title": "Roadmap" } ], "next_cursor": "eyJpZCI6Mn0.cuGm7m76S3bOizAsEbyVpHEsw-5bafeEGFHJ26VFq-E" } 200 application/json { "items": [ { "id": 3, "title": "Hiring" } ] } 400 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_query", "title": "The query string could not be parsed.", "status": 400, "code": "malformed_query", "errors": [ { "in": "query", "name": "cursor", "code": "invalid_cursor", "detail": "is not a cursor issued for this query" } ] }
Example (QueryErrors) ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/whilesmartgo/apicontract"
)
func serve(h http.Handler, method, target, body string) {
request := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request)
show(recorder)
}
func show(recorder *httptest.ResponseRecorder) {
var indented bytes.Buffer
body := bytes.TrimSpace(recorder.Body.Bytes())
if err := json.Indent(&indented, body, "", " "); err != nil {
indented.Write(body)
}
fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}
type eventsList struct {
apicontract.Page
apicontract.Range
PageSize int `query:"page_size" deprecated:"limit"`
}
func listEvents(w http.ResponseWriter, r *http.Request) {
var q eventsList
if err := apicontract.BindQuery(r, &q); err != nil {
_ = apicontract.WriteProblem(w, err)
return
}
_ = apicontract.WriteJSON(w, http.StatusOK, map[string]any{"limit": q.Limit})
}
func main() {
h := http.HandlerFunc(listEvents)
serve(h, "GET", "/events?limit=ten", "")
serve(h, "GET", "/events?from=2026-11-15&to=2026-11-14&colour=red", "")
}
Output: 400 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_query", "title": "The query string could not be parsed.", "status": 400, "code": "malformed_query", "errors": [ { "in": "query", "name": "limit", "code": "invalid", "detail": "must be an integer" } ] } 422 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_query", "title": "The query string is not valid.", "status": 422, "code": "invalid_query", "errors": [ { "in": "query", "name": "colour", "code": "unknown_field", "detail": "is not a parameter of this route" }, { "in": "query", "name": "to", "code": "out_of_range", "detail": "must be after from" } ] }
Example (RenamedParameter) ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"github.com/whilesmartgo/apicontract"
)
func serve(h http.Handler, method, target, body string) {
request := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request)
show(recorder)
}
func show(recorder *httptest.ResponseRecorder) {
var indented bytes.Buffer
body := bytes.TrimSpace(recorder.Body.Bytes())
if err := json.Indent(&indented, body, "", " "); err != nil {
indented.Write(body)
}
fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}
type eventsList struct {
apicontract.Page
apicontract.Range
PageSize int `query:"page_size" deprecated:"limit"`
}
func listEvents(w http.ResponseWriter, r *http.Request) {
var q eventsList
if err := apicontract.BindQuery(r, &q); err != nil {
_ = apicontract.WriteProblem(w, err)
return
}
_ = apicontract.WriteJSON(w, http.StatusOK, map[string]any{"limit": q.Limit})
}
func main() {
h := http.HandlerFunc(listEvents)
serve(h, "GET", "/events?page_size=20", "")
serve(h, "GET", "/events?page_size=20&limit=30", "")
}
Output: 200 application/json { "limit": 20 } 422 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_query", "title": "The query string is not valid.", "status": 422, "code": "invalid_query", "errors": [ { "in": "query", "name": "page_size", "code": "conflict", "detail": "page_size and limit disagree; send only limit" } ] }
Example (RequestBody) ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/whilesmartgo/apicontract"
)
func serve(h http.Handler, method, target, body string) {
request := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request)
show(recorder)
}
func show(recorder *httptest.ResponseRecorder) {
var indented bytes.Buffer
body := bytes.TrimSpace(recorder.Body.Bytes())
if err := json.Indent(&indented, body, "", " "); err != nil {
indented.Write(body)
}
fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}
type newEvent struct {
Title string `json:"title" required:"true" maxLength:"200"`
StartsAt time.Time `json:"starts_at" required:"true"`
Capacity *int `json:"capacity" minimum:"1"`
Attendees []struct {
Email string `json:"email" required:"true"`
} `json:"attendees" maxItems:"50"`
}
func createEventHandler(w http.ResponseWriter, r *http.Request) {
var body newEvent
if err := apicontract.BindJSON(r, &body); err != nil {
_ = apicontract.WriteProblem(w, err)
return
}
_ = apicontract.WriteJSON(w, http.StatusCreated, body)
}
func main() {
h := http.HandlerFunc(createEventHandler)
serve(h, "POST", "/events", `{"title": "Planning", "starts_at": "2026-11-14T09:00:00+01:00", "attendees": [{"email": "ada@example.com"}]}`)
serve(h, "POST", "/events", `{"starts_at": "2026-11-14T09:00:00", "capacity": 0, "attendees": [{"name": "Ada"}]}`)
serve(h, "POST", "/events", `{"capacity": 0, "attendees": [{"name": "Ada"}]}`)
}
Output: 201 application/json { "title": "Planning", "starts_at": "2026-11-14T09:00:00+01:00", "capacity": null, "attendees": [ { "email": "ada@example.com" } ] } 400 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_body", "title": "The request body could not be parsed.", "status": 400, "code": "malformed_body", "errors": [ { "in": "body", "name": "title", "code": "required", "detail": "is required" }, { "in": "body", "name": "starts_at", "code": "invalid", "detail": "must be an RFC 3339 timestamp with offset, such as 2026-11-14T09:00:00+01:00" }, { "in": "body", "name": "capacity", "code": "out_of_range", "detail": "must be at least 1" }, { "in": "body", "name": "attendees[0].name", "code": "unknown_field", "detail": "is not a field of this request" }, { "in": "body", "name": "attendees[0].email", "code": "required", "detail": "is required" } ] } 422 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#invalid_body", "title": "The request body is not valid.", "status": 422, "code": "invalid_body", "errors": [ { "in": "body", "name": "title", "code": "required", "detail": "is required" }, { "in": "body", "name": "starts_at", "code": "required", "detail": "is required" }, { "in": "body", "name": "capacity", "code": "out_of_range", "detail": "must be at least 1" }, { "in": "body", "name": "attendees[0].name", "code": "unknown_field", "detail": "is not a field of this request" }, { "in": "body", "name": "attendees[0].email", "code": "required", "detail": "is required" } ] }
Example (RequestBodyRejected) ¶
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
"github.com/whilesmartgo/apicontract"
)
func serve(h http.Handler, method, target, body string) {
request := httptest.NewRequest(method, target, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request)
show(recorder)
}
func show(recorder *httptest.ResponseRecorder) {
var indented bytes.Buffer
body := bytes.TrimSpace(recorder.Body.Bytes())
if err := json.Indent(&indented, body, "", " "); err != nil {
indented.Write(body)
}
fmt.Printf("%d %s\n%s\n", recorder.Code, recorder.Header().Get("Content-Type"), indented.String())
}
type newEvent struct {
Title string `json:"title" required:"true" maxLength:"200"`
StartsAt time.Time `json:"starts_at" required:"true"`
Capacity *int `json:"capacity" minimum:"1"`
Attendees []struct {
Email string `json:"email" required:"true"`
} `json:"attendees" maxItems:"50"`
}
func createEventHandler(w http.ResponseWriter, r *http.Request) {
var body newEvent
if err := apicontract.BindJSON(r, &body); err != nil {
_ = apicontract.WriteProblem(w, err)
return
}
_ = apicontract.WriteJSON(w, http.StatusCreated, body)
}
func main() {
h := http.HandlerFunc(createEventHandler)
request := httptest.NewRequest("POST", "/events", strings.NewReader("title=Planning"))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
recorder := httptest.NewRecorder()
h.ServeHTTP(recorder, request)
show(recorder)
serve(h, "POST", "/events", `{"title": "a", "title": "b"}`)
}
Output: 415 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#unsupported_media_type", "title": "The request body must be JSON.", "status": 415, "detail": "Send the body as application/json.", "code": "unsupported_media_type" } 400 application/problem+json { "type": "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_body", "title": "The request body could not be parsed.", "status": 400, "detail": "The request body is not valid JSON: duplicate key \"title\".", "code": "malformed_body" }
Index ¶
- Constants
- func BindJSON(r *http.Request, dst any, options ...BodyOption) error
- func BindJSONBytes(data []byte, dst any, options ...BodyOption) error
- func BindQuery(r *http.Request, dst any) error
- func BindValues(values url.Values, dst any) error
- func BodySchema(v any) (map[string]any, error)
- func ErrorSchema() map[string]any
- func IdempotencyKey(r *http.Request) (string, error)
- func InputSchema(v any) (map[string]any, error)
- func OpenAPIParameters(v any) ([]map[string]any, error)
- func OpenAPIParametersOf(fields []Field) ([]map[string]any, error)
- func OpenAPIProblemResponse(status int) map[string]any
- func OpenAPIRequestBody(v any) (map[string]any, error)
- func OpenAPIRequestBodyOf(fields []Field) (map[string]any, error)
- func QueryBinding(values url.Values, principal ...string) string
- func RequestBinding(r *http.Request, principal ...string) string
- func WriteError(w http.ResponseWriter, status int, code, detail string, errors ...FieldError) error
- func WriteJSON(w http.ResponseWriter, status int, value any) error
- func WriteList[T any](w http.ResponseWriter, items []T, next string) error
- func WriteProblem(w http.ResponseWriter, err error) error
- type BodyOption
- type Cursors
- type Date
- type Field
- type FieldError
- type FieldType
- type List
- type Page
- type Problem
- type Range
- type Search
- type SortKey
- type Zone
Examples ¶
Constants ¶
const ( CodeMalformedQuery = "malformed_query" CodeInvalidQuery = "invalid_query" CodeMalformedBody = "malformed_body" CodeInvalidBody = "invalid_body" CodeUnsupportedMediaType = "unsupported_media_type" CodeBodyTooLarge = "body_too_large" CodeMalformedHeader = "malformed_header" CodeInternal = "internal_error" )
Problem codes written in Problem.Code.
const ( FieldInvalid = "invalid" FieldRequired = "required" FieldOutOfRange = "out_of_range" FieldTooLong = "too_long" FieldTooMany = "too_many" FieldUnknownValue = "unknown_value" FieldUnknown = "unknown_field" FieldConflict = "conflict" FieldInvalidCursor = "invalid_cursor" )
Field error codes written in FieldError.Code.
const ( InQuery = "query" InBody = "body" InHeader = "header" )
Where a FieldError points, written in FieldError.In.
const ( DefaultLimit = 50 MaxLimit = 200 MaxCursorLength = 2048 )
const DefaultMaxBodyBytes = 1 << 20
DefaultMaxBodyBytes is the request body size BindJSON accepts unless MaxBytes says otherwise.
const IdempotencyHeader = "Idempotency-Key"
IdempotencyHeader is the request header that carries an idempotency key.
const ProblemContentType = "application/problem+json"
ProblemContentType is the media type of every error response (RFC 9457).
const ProblemTypeBase = "https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#"
ProblemTypeBase prefixes the type URI of the problems this package writes. Each code has a section in docs/errors.md.
const Version = "0.1"
Version is the contract version this module implements. An OpenAPI document states the version it meets in info.x-whilesmart-contract.
const VersionExtension = "x-whilesmart-contract"
VersionExtension is the OpenAPI info extension that carries Version.
Variables ¶
This section is empty.
Functions ¶
func BindJSON ¶ added in v0.1.1
func BindJSON(r *http.Request, dst any, options ...BodyOption) error
BindJSON reads the request's JSON body into dst, a pointer to a struct whose fields carry json tags and the same rule tags as query structs. It returns a *Problem with status 415 when the body is not JSON, 413 when it is larger than the limit, 400 when it cannot be parsed or a value has the wrong type, and 422 when a parsed value breaks a rule, including a field the struct does not declare. Any other error means dst is not a valid body struct.
func BindJSONBytes ¶ added in v0.1.1
func BindJSONBytes(data []byte, dst any, options ...BodyOption) error
BindJSONBytes parses a JSON object, such as a request body or a tool call's arguments, into dst, with the same size limit and rules as BindJSON.
func BindQuery ¶
BindQuery parses the request's query string into dst, a pointer to a struct whose fields carry query tags. It returns a *Problem with status 400 when a value cannot be parsed and 422 when a parsed value breaks a rule, including a parameter the struct does not declare. Any other error means dst is not a valid parameter struct.
func BindValues ¶
BindValues parses values into dst. See BindQuery.
func BodySchema ¶ added in v0.1.1
BodySchema describes the body struct value v as a JSON Schema object, as BindJSON reads it. Use it for tool input schemas and request body schemas.
Example ¶
package main
import (
"encoding/json"
"fmt"
"time"
"github.com/whilesmartgo/apicontract"
)
type newEvent struct {
Title string `json:"title" required:"true" maxLength:"200"`
StartsAt time.Time `json:"starts_at" required:"true"`
Capacity *int `json:"capacity" minimum:"1"`
Attendees []struct {
Email string `json:"email" required:"true"`
} `json:"attendees" maxItems:"50"`
}
func main() {
schema, _ := apicontract.BodySchema(newEvent{})
data, _ := json.MarshalIndent(schema, "", " ")
fmt.Println(string(data))
}
Output: { "additionalProperties": false, "properties": { "attendees": { "items": { "additionalProperties": false, "properties": { "email": { "type": "string" } }, "required": [ "email" ], "type": "object" }, "maxItems": 50, "type": "array" }, "capacity": { "minimum": 1, "type": [ "integer", "null" ] }, "starts_at": { "format": "date-time", "type": "string" }, "title": { "maxLength": 200, "type": "string" } }, "required": [ "title", "starts_at" ], "type": "object" }
func ErrorSchema ¶ added in v0.1.1
ErrorSchema returns the JSON Schema of the problem body, as published in schema/error.json, without its $schema and $id keywords.
func IdempotencyKey ¶ added in v0.1.1
IdempotencyKey returns the request's Idempotency-Key, or an empty string when the header is absent. The key is a Structured Field String as the IETF draft specifies, such as "8e03978e-40d5-43e8-bc93-6894a57f9324" with the quotes, or a bare key of visible ASCII without commas, quotes or backslashes. The decoded key must be 8 to 128 characters. A key sent more than once, in separate fields or joined by a comma, or one that cannot be parsed returns a *Problem with status 400. Storing keys and replaying responses is left to the app.
Example ¶
package main
import (
"encoding/json"
"fmt"
"net/http/httptest"
"github.com/whilesmartgo/apicontract"
)
func main() {
request := httptest.NewRequest("POST", "/events", nil)
request.Header.Set("Idempotency-Key", "short")
_, err := apicontract.IdempotencyKey(request)
data, _ := json.Marshal(err)
fmt.Println(string(data))
}
Output: {"type":"https://github.com/whilesmartgo/apicontract/blob/main/docs/errors.md#malformed_header","title":"A request header could not be parsed.","status":400,"code":"malformed_header","errors":[{"in":"header","name":"Idempotency-Key","code":"invalid","detail":"must be 8 to 128 characters"}]}
func InputSchema ¶
InputSchema describes the query parameters of the struct value v as a JSON Schema object. Use it for tool input schemas so tools accept the same names, formats and bounds as the HTTP route.
func OpenAPIParameters ¶
OpenAPIParameters describes the parameters of the struct value v as OpenAPI 3.1 query parameter objects, for specs that are built in code.
func OpenAPIParametersOf ¶
OpenAPIParametersOf is OpenAPIParameters for a struct described by fields instead of a value.
func OpenAPIProblemResponse ¶ added in v0.1.1
OpenAPIProblemResponse returns an OpenAPI response object for an error status, with the problem body under application/problem+json.
func OpenAPIRequestBody ¶ added in v0.1.1
OpenAPIRequestBody describes the body struct value v as an OpenAPI 3.1 request body object.
func OpenAPIRequestBodyOf ¶ added in v0.1.1
OpenAPIRequestBodyOf is OpenAPIRequestBody for a struct described by fields instead of a value.
func QueryBinding ¶
QueryBinding returns a binding for a cursor from the query values that shape the result and from the principal parts. Prefer RequestBinding, which also binds the route; QueryBinding alone lets a cursor from one route verify on another route with the same query and caller.
func RequestBinding ¶ added in v0.1.1
RequestBinding returns a binding for a cursor from the request's method and path, the query values that shape the result, and the principal parts, such as user and owner IDs. A cursor bound this way is rejected on another route, on the same route for another resource, with another filter, or for another caller. cursor and limit are left out so a client can change the page size between pages.
func WriteError ¶
func WriteError(w http.ResponseWriter, status int, code, detail string, errors ...FieldError) error
WriteError writes a problem with status, code and detail.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, value any) error
WriteJSON writes value as JSON with the given status.
func WriteList ¶
func WriteList[T any](w http.ResponseWriter, items []T, next string) error
WriteList writes a 200 response with the list envelope.
func WriteProblem ¶
func WriteProblem(w http.ResponseWriter, err error) error
WriteProblem writes err as a problem. Errors that are not a *Problem are written as a 500 without exposing their text.
Types ¶
type BodyOption ¶ added in v0.1.1
type BodyOption func(*bodyConfig)
BodyOption configures BindJSON.
func MaxBytes ¶ added in v0.1.1
func MaxBytes(n int64) BodyOption
MaxBytes sets the largest body BindJSON and BindJSONBytes accept. It must be positive.
type Cursors ¶
type Cursors struct {
// contains filtered or unexported fields
}
Cursors signs and verifies opaque cursors. A cursor carries a JSON position and a MAC over the position and a binding, so it is rejected when replayed against a different query or principal. Positions are readable by anyone who decodes the cursor; do not put secrets in them.
func NewCursors ¶
NewCursors returns a Cursors signing with key, which must be at least 32 bytes.
type Date ¶ added in v0.1.1
Date is a calendar day with no time or zone, written as YYYY-MM-DD.
func (Date) MarshalJSON ¶ added in v0.1.1
func (*Date) UnmarshalJSON ¶ added in v0.1.1
type Field ¶
type Field struct {
Name string
Exported bool
Anonymous bool
Type FieldType
Tag reflect.StructTag
// Pointer is true when the field is a pointer to Type. A pointer body
// field accepts null.
Pointer bool
// Bits is the size of an integer or floating-point type, such as 8 for
// int8. Zero means 64.
Bits int
// Range is true when the field's type is apicontract.Range.
Range bool
// Fields holds the nested fields when Type is FieldStruct.
Fields []Field
// Elem describes the element type when Type is FieldList.
Elem *Field
}
Field describes one struct field. Static tools that read Go source, such as OpenAPI generators, build Fields from the source types and pass them to OpenAPIParametersOf or OpenAPIRequestBodyOf, so they describe a struct exactly as BindQuery and BindJSON read it. Fields lists every field of the struct in order.
type FieldError ¶
type FieldError struct {
In string `json:"in"`
Name string `json:"name"`
Code string `json:"code"`
Detail string `json:"detail"`
}
FieldError is one input at fault. Name is the query parameter, the header, or the body field path as the client sent it, such as attendees[2].email.
type FieldType ¶
type FieldType int
FieldType classifies a struct field for parameter and body description.
type List ¶
type List[T any] struct { Items []T `json:"items"` NextCursor string `json:"next_cursor,omitempty"` Total *int `json:"total,omitempty"` }
List is the response envelope for collection routes. NextCursor is empty on the last page. Total is set only when it is exact and cheap to compute.
type Page ¶
type Page struct {
Limit int `` /* 135-byte string literal not displayed */
Cursor string `` /* 141-byte string literal not displayed */
}
Page holds cursor paging parameters. Limit defaults to DefaultLimit and is clamped to MaxLimit.
type Problem ¶
type Problem struct {
Type string `json:"type,omitempty"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Code string `json:"code"`
Errors []FieldError `json:"errors,omitempty"`
}
Problem is an error that is written as an RFC 9457 problem details object. Code and Errors are extension members.
func NewProblem ¶ added in v0.1.1
func NewProblem(status int, code, detail string, errors ...FieldError) *Problem
NewProblem returns a problem with status and code. Codes defined by this package get their documented type and title; other codes get the status text as title and no type, which RFC 9457 reads as about:blank.
type Range ¶
type Range struct {
From time.Time `` /* 132-byte string literal not displayed */
To time.Time `query:"to" bound:"end" doc:"End of the range. A timestamp is exclusive. A YYYY-MM-DD day includes that whole day."`
}
Range is a half-open time range [From, To). A day value (YYYY-MM-DD) in From means the start of that day; in To it means the end of that day. Days are resolved in the request Zone, or UTC when the struct has no Zone.
Embedded without a query tag the parameters are from and to. As a named field with query:"updated" they are updated_from and updated_to.
type Search ¶
type Search struct {
Q string `query:"q" maxLength:"500" doc:"Free-text search."`
}
Search holds the free-text search parameter.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
apicontract
command
Command apicontract checks OpenAPI documents against the API contract.
|
Command apicontract checks OpenAPI documents against the API contract. |
|
Package lint checks an OpenAPI document against the API contract.
|
Package lint checks an OpenAPI document against the API contract. |