sonda/internal/api/http/docs.go
tgiachi 9d28a8a99c feat(api): OpenAPI spec and an offline Swagger UI
- feat: internal/api/openapi/openapi.yaml describes every operation (OpenAPI
  3.0.3), written by hand and embedded in the binary; GET /api/v1/openapi.yaml
  serves it
- feat: GET /api/docs/ serves Swagger UI from assets embedded in the binary
  (github.com/swaggest/swgui, v5emb), so opening it never contacts another
  server; both are public because they contain no data
- feat: response objects in the spec are closed (additionalProperties: false)
- test: the spec is valid OpenAPI; the router and the spec describe the same
  operations in both directions; every operation has an id, a summary, a tag,
  a documented 401 when it needs a token and a 403 when it is admin only
- test: a contract test drives every operation through the real services,
  including a real scan and real streaming, and validates each response
  (status, headers, JSON body) against the spec with kin-openapi; it fails if
  an operation was never exercised. Checked by breaking the code and the spec
  on purpose
- test: the docs page loads without any external address and every asset it
  references is served
- docs: README section on the interactive documentation and on keeping the
  spec in step with the code

Closes #15
2026-11-11 14:35:16 +01:00

29 lines
857 B
Go

package httpapi
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/swaggest/swgui/v5emb"
"codeberg.org/squidd/sonda/internal/api/openapi"
)
const (
specPath = "/api/v1/openapi.yaml"
docsPath = "/api/docs/"
)
// registerDocs serves the OpenAPI spec and a Swagger UI for it. Both are public:
// they describe the API and contain no data. The UI's assets are embedded in the
// binary, so opening it never contacts another server.
func registerDocs(r *gin.Engine, v1 *gin.RouterGroup) {
v1.GET("/openapi.yaml", func(c *gin.Context) {
c.Header("Cache-Control", "no-cache")
c.Data(http.StatusOK, "application/yaml; charset=utf-8", openapi.Spec)
})
ui := v5emb.New("Sonda API", specPath, docsPath)
r.GET("/api/docs", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, docsPath) })
r.GET("/api/docs/*any", gin.WrapH(ui))
}