1 Home
Virgil edited this page 2026-03-11 12:06:34 +00:00

go-api

Module: forge.lthn.ai/core/go-api

Gin-based REST API framework with functional options for middleware, OpenAPI generation, WebSocket support, SSE streaming, GraphQL, and Authentik forward-auth. Provides a standard response envelope and route group pattern for modular API design.

Architecture

File Purpose
api.go Engine — central server with New(), Register(), Serve(), Handler()
group.go RouteGroup, StreamGroup, DescribableGroup interfaces
options.go 20+ functional options: auth, CORS, compression, caching, sessions, etc.
response.go Generic Response[T] envelope: OK(), Fail(), Paginated()
middleware.go Bearer auth, request ID middleware
openapi.go OpenAPI spec generation from DescribableGroup
swagger.go Swagger UI mounting
sse.go SSEBroker — Server-Sent Events
websocket.go WebSocket handler bridge
graphql.go GraphQL endpoint with gqlgen
authentik.go Authentik forward-auth middleware
bridge.go Bridge utilities
brotli.go Brotli compression middleware
cache.go In-memory response caching
codegen.go Code generation helpers
export.go API export utilities
i18n.go Internationalisation middleware
tracing.go Request tracing

CLI commands in cmd/api/ (sdk, spec, test).

Key Types

Core

  • Engine — API server: New(opts...), Register(group), Serve(ctx), Handler(), Channels(), GroupsIter()
  • RouteGroup interface — Name(), BasePath(), RegisterRoutes(rg *gin.RouterGroup)
  • StreamGroup interface — Channels() []string (for WebSocket channel declaration)
  • DescribableGroup interface — Extends RouteGroup with Describe() []RouteDescription for OpenAPI
  • RouteDescriptionMethod, Path, Summary, Description, Tags, RequestBody, Response

Response Envelope

  • Response[T] — Generic envelope: Success bool, Data T, Error *Error, Meta *Meta
  • ErrorCode, Message, Details
  • MetaRequestID, Duration, Page, PerPage, Total
  • OK[T](data) — Success response
  • Fail(code, message) — Error response
  • Paginated[T](data, page, perPage, total) — Paginated success

Streaming

  • SSEBroker — Server-Sent Events broker at /events
  • WebSocket handler bridge at /ws

Usage

import "forge.lthn.ai/core/go-api"

engine, _ := api.New(
    api.WithAddr(":8080"),
    api.WithCORS("*"),
    api.WithBearerAuth("secret-token"),
    api.WithSwagger("My API", "Description", "v1"),
    api.WithGzip(),
    api.WithTimeout(30 * time.Second),
    api.WithCache(5 * time.Minute),
)

engine.Register(myRouteGroup)
engine.Serve(ctx)

Dependencies

  • github.com/gin-gonic/gin — HTTP router
  • github.com/gin-contrib/* — Middleware (cors, gzip, sessions, secure, timeout, pprof, expvar, slog, static, httpsign, location, authz)
  • github.com/99designs/gqlgen — GraphQL
  • github.com/casbin/casbin/v2 — Policy-based authorisation