-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
openapi_handler.go
61 lines (48 loc) · 1.35 KB
/
openapi_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package v1
import (
_ "embed" // imported for openapi specification embedding
"fmt"
"net/http"
"github.com/getkin/kin-openapi/openapi3"
"github.com/labstack/echo/v4"
"github.com/rs/zerolog"
)
//go:embed REST/openapi.yaml
var openAPI []byte
type OpenAPIHandler struct {
OpenAPI *openapi3.T
*zerolog.Logger
swaggerJSON []byte
}
func (h *OpenAPIHandler) ServeOpenAPI(ctx echo.Context) error {
var err error
switch ctx.Request().Header.Get(echo.HeaderContentType) {
case echo.MIMEApplicationJSON:
fallthrough
case echo.MIMEApplicationJSONCharsetUTF8:
err = ctx.JSONBlob(http.StatusOK, h.swaggerJSON)
default:
err = ctx.Blob(http.StatusOK, "text/yaml", openAPI)
}
if err != nil {
return fmt.Errorf("could not write openapi definition into response: %w", err)
}
return nil
}
func NewOpenAPIHandler(openAPI *openapi3.T, logger *zerolog.Logger) *OpenAPIHandler {
serversToLog := zerolog.Arr()
for _, server := range openAPI.Servers {
serversToLog = serversToLog.Str(server.URL)
}
log := logger.With().
Str("api", openAPI.Info.Title).
Str("version", openAPI.Info.Version).
Array("servers", serversToLog).
Logger()
swaggerJSON, err := openAPI.MarshalJSON()
if err != nil {
log.Error().Err(err).Msg("could not marshal swagger json into memory")
}
log.Info().Msg("API Loaded!")
return &OpenAPIHandler{openAPI, &log, swaggerJSON}
}