-
Notifications
You must be signed in to change notification settings - Fork 3
/
swagserver.go
98 lines (80 loc) · 2.39 KB
/
swagserver.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//go:generate statik -src=./tmp
package swagserver
import (
"html/template"
"io"
"log"
"net/http"
"net/url"
"strings"
"github.com/rakyll/statik/fs"
"github.com/syllabix/swagserver/config"
// This empty import is required to initialize the embedded swagger files
_ "github.com/syllabix/swagserver/statik"
)
// Middleware is a simple alias for a commonmiddle ware function signature, func(next http.Handler) http.Handler
type Middleware func(next http.Handler) http.Handler
const (
fatalMsg = `
An error occurred while initializing swagserver middlware.
This is most likely a problem with the swagserver package itself.
Please file an issue on github @ github.com/syllabix/swagserver`
)
func setup() (fileserver http.Handler, tmpl *template.Template, err error) {
statikFs, err := fs.New()
if err != nil {
return nil, nil, err
}
swaggerui, err := statikFs.Open("/index.html")
if err != nil {
return nil, nil, err
}
defer swaggerui.Close()
var builder strings.Builder
_, err = io.Copy(&builder, swaggerui)
if err != nil {
return nil, nil, err
}
fileserver = http.FileServer(statikFs)
tmpl, err = template.New("swaggerui").Parse(builder.String())
return
}
// New is the factory constructor for intializing a middleware
// using config.Option funcs to override defaults settings
func New(options ...config.Option) Middleware {
handler, settings := handlerAndSettings(options...)
shouldServe := func(url *url.URL) bool {
return settings.ShouldRender &&
strings.HasPrefix(url.Path, settings.URLPath)
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !shouldServe(r.URL) {
next.ServeHTTP(w, r)
} else {
handler.ServeHTTP(w, r)
}
})
}
}
// NewHandler returns an http.Handler that serves the swagger UI. This
// constructor ignores the `Path` option
func NewHandler(options ...config.Option) http.Handler {
handler, _ := handlerAndSettings(options...)
return handler
}
func handlerAndSettings(options ...config.Option) (http.Handler, config.Settings) {
fileserver, template, err := setup()
if err != nil {
log.Fatal(fatalMsg, err)
}
settings := settings(options...)
return newhandler(settings, fileserver, template), settings
}
func settings(options ...config.Option) config.Settings {
settings := config.DefaultSettings
for _, opt := range options {
opt(&settings)
}
return settings
}