Newer
Older
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cmd
import (
"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 {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
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)
}
}