forked from lazada/swgui
-
Notifications
You must be signed in to change notification settings - Fork 8
/
handler.go
63 lines (47 loc) · 1.42 KB
/
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
62
63
// Package internal provides internal handler implementation.
package internal
import (
"encoding/json"
"html/template"
"net/http"
"strings"
"github.com/swaggest/swgui"
)
// Handler handles swagger UI request.
type Handler struct {
swgui.Config
ConfigJson template.JS
tpl *template.Template
staticServer http.Handler
}
// NewHandlerWithConfig returns a HTTP handler for swagger UI.
func NewHandlerWithConfig(config swgui.Config, assetsBase, faviconBase string, staticServer http.Handler) *Handler {
config.BasePath = strings.TrimSuffix(config.BasePath, "/") + "/"
h := &Handler{
Config: config,
}
j, err := json.Marshal(h.Config)
if err != nil {
panic(err)
}
h.ConfigJson = template.JS(j) // nolint:gosec // Data is well formed.
h.tpl, err = template.New("index").Parse(IndexTpl(assetsBase, faviconBase, config))
if err != nil {
panic(err)
}
if staticServer != nil {
h.staticServer = http.StripPrefix(h.BasePath, staticServer)
}
return h
}
// ServeHTTP implements http.Handler interface to handle swagger UI request.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if strings.TrimSuffix(r.URL.Path, "/") != strings.TrimSuffix(h.BasePath, "/") && h.staticServer != nil {
h.staticServer.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Type", "text/html")
if err := h.tpl.Execute(w, h); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}