57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package port
|
|
|
|
import (
|
|
"net/http"
|
|
"sync"
|
|
|
|
"gitea.dwysokinski.me/twhelp/corev3/internal/app"
|
|
"gitea.dwysokinski.me/twhelp/corev3/internal/port/internal/apimodel"
|
|
"gitea.dwysokinski.me/twhelp/corev3/internal/port/internal/swgui"
|
|
"github.com/getkin/kin-openapi/openapi3"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/render"
|
|
)
|
|
|
|
type apiHTTPHandler struct {
|
|
versionSvc *app.VersionService
|
|
getOpenAPISchema func() (*openapi3.T, error)
|
|
}
|
|
|
|
func WithOpenAPIConfig(oapiCfg OpenAPIConfig) APIHTTPHandlerOption {
|
|
return func(cfg *apiHTTPHandlerConfig) {
|
|
cfg.openAPI = oapiCfg
|
|
}
|
|
}
|
|
|
|
func NewAPIHTTPHandler(versionSvc *app.VersionService, opts ...APIHTTPHandlerOption) http.Handler {
|
|
cfg := newAPIHTTPHandlerConfig(opts...)
|
|
|
|
h := &apiHTTPHandler{
|
|
versionSvc: versionSvc,
|
|
getOpenAPISchema: sync.OnceValues(func() (*openapi3.T, error) {
|
|
return getOpenAPISchema(cfg.openAPI)
|
|
}),
|
|
}
|
|
|
|
r := chi.NewRouter()
|
|
|
|
if cfg.openAPI.Enabled {
|
|
r.Group(func(r chi.Router) {
|
|
if cfg.openAPI.SwaggerEnabled {
|
|
r.Handle("/v2/swagger/*", swgui.Handler(
|
|
cfg.openAPI.BasePath+"/v2/swagger",
|
|
cfg.openAPI.BasePath+"/v2/openapi3.json",
|
|
))
|
|
}
|
|
r.Get("/v2/openapi3.json", h.sendOpenAPIJSON)
|
|
})
|
|
}
|
|
|
|
return apimodel.HandlerWithOptions(h, apimodel.ChiServerOptions{BaseRouter: r})
|
|
}
|
|
|
|
func (h *apiHTTPHandler) renderJSON(w http.ResponseWriter, r *http.Request, status int, body any) {
|
|
render.Status(r, status)
|
|
render.JSON(w, r, body)
|
|
}
|