api

package
v1.7.7 Latest Latest
Warning

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

Go to latest
Published: Apr 17, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound   = errors.New("not found")
	ErrBadRequest = errors.New("bad request")
	ErrForbidden  = errors.New("forbidden")
)

Sentinel errors that handlers can return to produce specific HTTP status codes.

Functions

func BuildOpenAPI

func BuildOpenAPI(title, version string) openAPISchema

BuildOpenAPI constructs the OpenAPI spec from all registered routes. Exported so the codegen command can call it directly to write openapi.json.

func HealthHandler

func HealthHandler() http.Handler

HealthHandler returns an http.Handler that reports the health of the service and database. GET /api/health → {"status":"ok","db":"ok"} or {"status":"error","db":"error: ..."}

func InitAuth

func InitAuth(key []byte)

InitAuth sets the HMAC-SHA256 signing key used for JWT verification. Called by the schemaf app after migrations run and the key is loaded from _schemaf_config.

func IssueToken

func IssueToken(sub string, exp time.Time) (string, error)

IssueToken creates a signed JWT for the given subject. exp=0 means no expiry.

func NewMux

func NewMux() *http.ServeMux

NewMux builds and returns the http.ServeMux with all framework defaults and registered routes. Useful for testing with httptest.NewServer.

func OpenAPIHandler

func OpenAPIHandler() http.Handler

OpenAPIHandler returns an http.Handler that serves an OpenAPI 3.0 JSON document reflecting all registered routes.

func Register

func Register(r Route)

Register adds a route to the global registry.

func RegisterHealth added in v1.5.0

func RegisterHealth(name string, fn HealthChecker)

RegisterHealth adds a named health check. If the checker returns an error, the overall health status is "error" and the response code is 503.

api.RegisterHealth("s3", func() error {
    return s3Client.Ping()
})

func RegisterStatus added in v1.4.0

func RegisterStatus(name string, fn StatusProvider)

RegisterStatus adds a named status provider. The returned value is included under the given key in the /api/status JSON response.

api.RegisterStatus("s3", func() any {
    return map[string]any{"bucket": "my-bucket", "connected": true}
})

func Reset

func Reset()

Reset clears all registered routes. Intended for use in tests only.

func Serve

func Serve(addr string) error

Serve starts the HTTP server on the given address using the registered routes. addr should be in the form ":8000".

func SetFrontend added in v0.7.0

func SetFrontend(fsys fs.FS)

SetFrontend registers the embedded frontend filesystem for production serving. In dev mode (SCHEMAF_ENV != "docker"), the server proxies to the frontend dev server instead.

func StatusHandler

func StatusHandler() http.Handler

StatusHandler returns an http.Handler for GET /api/status. Reports service uptime, last backup status, and any registered status providers. Always open (no auth required).

func Subject

func Subject(ctx context.Context) (string, bool)

Subject returns the authenticated subject (user ID) from the context. Returns ("", false) if the request was not authenticated.

func UserMeHandler

func UserMeHandler() http.Handler

UserMeHandler returns an http.Handler for GET /api/user/me. Requires a valid JWT — returns the authenticated user's UUID from the sub claim.

Types

type Endpoint

type Endpoint[Req, Resp any] interface {
	Method() string // HTTP method: "GET", "POST", "PUT", "DELETE", etc.
	Path() string   // Route path, e.g. "/api/todos/{id}"
	Auth() bool     // Whether the endpoint requires JWT authentication
	Handle(ctx context.Context, req Req) (Resp, error)
}

Endpoint is the interface that all schemaf API endpoints must implement. Req is the request type (decoded from JSON body or path/query params). Resp is the response type (encoded as JSON).

Document your endpoint with a Go doc comment on the struct:

// ListTodosEndpoint returns all todo items ordered by creation date.
// Returns an empty array if no todos exist.
type ListTodosEndpoint struct{}

The first line becomes the OpenAPI summary; subsequent lines the description. Both are extracted by codegen — no annotations required.

type HealthChecker added in v1.5.0

type HealthChecker func() error

HealthChecker returns nil if healthy, or an error describing the problem.

type RawEndpoint added in v0.12.1

type RawEndpoint interface {
	Method() string
	Path() string
	Auth() bool
	HandleRaw(w http.ResponseWriter, r *http.Request) error
}

RawEndpoint is an alternative to Endpoint for handlers that need direct HTTP access — binary uploads, streaming downloads, SSE, etc.

Define HandleRaw instead of Handle on your endpoint struct. Exactly one of Handle or HandleRaw must be present; codegen will error if both exist.

The framework does not decode the request or encode the response — you have full control over http.ResponseWriter and *http.Request. If HandleRaw returns a non-nil error and no response has been written yet, the framework writes a JSON error response using the standard error mapping.

type Route

type Route struct {
	Method      string // "GET", "POST", "PUT", "DELETE", etc.
	Path        string // e.g. "/api/todos", "/api/todos/{id}"
	Auth        bool   // whether JWT auth is required
	Summary     string // first line of endpoint struct doc comment
	Description string // remaining lines of endpoint struct doc comment
	Handler     http.Handler
	ReqType     any // pointer to zero-value request type (for OpenAPI reflection)
	RespType    any // pointer to zero-value response type (for OpenAPI reflection)
}

Route describes a single HTTP route registered with the framework.

func NewRawRoute added in v0.12.1

func NewRawRoute(e RawEndpoint, summary, description string) Route

NewRawRoute creates a Route from a RawEndpoint. No JSON decode/encode is performed; the handler receives the raw http.ResponseWriter and *http.Request.

func NewRoute

func NewRoute[Req, Resp any](e Endpoint[Req, Resp], summary, description string) Route

NewRoute creates a Route from a typed Endpoint, wiring up JSON decode/encode and auth declaration. summary and description are extracted from the struct's doc comment by codegen and passed as string literals in the generated Provider().

func Routes

func Routes() []Route

Routes returns all registered routes.

type StatusProvider added in v1.4.0

type StatusProvider func() any

StatusProvider returns a value to include in the /api/status response.

Jump to

Keyboard shortcuts

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