-
Christophe de Vienne authoredChristophe de Vienne authored
oapi.go 1.60 KiB
package cmd
import (
"fmt"
"net/http"
"strconv"
"github.com/getkin/kin-openapi/openapi2"
"github.com/getkin/kin-openapi/openapi3"
)
type OpenAPIFile interface {
Info() *openapi3.Info
JSON() []byte
}
type openAPI2File struct {
oapi *openapi2.T
json []byte
}
func (f *openAPI2File) Info() *openapi3.Info {
return &f.oapi.Info
}
func (f *openAPI2File) JSON() []byte {
if f.json == nil {
b, err := f.oapi.MarshalJSON()
if err != nil {
panic(err)
}
f.json = b
}
return f.json
}
type openAPI3File struct {
oapi *openapi3.T
json []byte
}
func (f *openAPI3File) Info() *openapi3.Info {
return f.oapi.Info
}
func (f *openAPI3File) JSON() []byte {
if f.json == nil {
b, err := f.oapi.MarshalJSON()
if err != nil {
panic(err)
}
f.json = b
}
return f.json
}
func WithOpenAPI2(t *openapi2.T) Option {
return WithOpenAPI(&openAPI2File{t, nil})
}
func WithOpenAPI3(t *openapi3.T) Option {
return WithOpenAPI(&openAPI3File{t, nil})
}
func WithOpenAPI(oapi OpenAPIFile) Option {
return func(program *Program) {
program.Version.APIVersion = oapi.Info().Title + " " + oapi.Info().Version
WithMiddleware(func(next http.Handler) http.Handler {
fmt.Println("oapi middleware")
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
fmt.Println("oapi", r.URL.Path)
if r.URL.Path == "/swagger.json" {
json := oapi.JSON()
rw.Header().Set("Content-Type", "application/json")
rw.Header().Set("Content-Lenght", strconv.Itoa(len(json)))
rw.WriteHeader(200)
rw.Write(oapi.JSON())
} else {
next.ServeHTTP(rw, r)
}
})
})(program)
}
}