slack-verify-1770279078/pkg/openapi/docs.go
jordan 1fdadd126a
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
ci/woodpecker/manual/woodpecker Pipeline was successful
Initialize project from skeleton template
2026-02-05 08:11:19 +00:00

50 lines
1.2 KiB
Go

package openapi
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
scalargo "github.com/bdpiprava/scalar-go"
)
// Mount registers /docs and /openapi.json endpoints on the router.
func Mount(r chi.Router, spec *OpenAPISpec) {
// Serve OpenAPI JSON
r.Get("/openapi.json", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
specBytes, err := spec.JSON()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, _ = w.Write(specBytes)
})
// Serve Scalar docs UI
r.Get("/docs", func(w http.ResponseWriter, r *http.Request) {
scheme := "http"
if proto := r.Header.Get("X-Forwarded-Proto"); proto != "" {
scheme = proto
} else if r.TLS != nil {
scheme = "https"
}
specURL := fmt.Sprintf("%s://%s/openapi.json", scheme, r.Host)
html, err := scalargo.NewV2(
scalargo.WithSpecURL(specURL),
scalargo.WithDarkMode(),
)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = fmt.Fprint(w, html)
})
}