predictor/internal/api/docs/docs.go

48 lines
1.4 KiB
Go

// Package docs serves the human-facing API documentation: the OpenAPI
// document and a ReDoc rendering of it. The spec is embedded in the binary
// (see package apispec) so the documentation needs no external files or a
// separate server.
package docs
import (
"net/http"
apispec "predictor-refactored/api"
)
// redocHTML renders the embedded spec with ReDoc loaded from a CDN.
const redocHTML = `<!DOCTYPE html>
<html>
<head>
<title>stratoflights-predictor API</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>body { margin: 0; padding: 0; }</style>
</head>
<body>
<redoc spec-url="/openapi.yaml"></redoc>
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
</body>
</html>`
// Handler serves the documentation endpoints.
type Handler struct{}
// New returns a docs Handler.
func New() *Handler { return &Handler{} }
// Register installs GET /docs and GET /openapi.yaml on mux.
func (h *Handler) Register(mux *http.ServeMux) {
mux.HandleFunc("GET /openapi.yaml", h.spec)
mux.HandleFunc("GET /docs", h.redoc)
}
func (h *Handler) spec(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/yaml")
_, _ = w.Write(apispec.Spec)
}
func (h *Handler) redoc(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = w.Write([]byte(redocHTML))
}