...
1 package middleware
2
3 import (
4 "bytes"
5 "fmt"
6 "html/template"
7 "net/http"
8 "path"
9 )
10
11
12 type RapiDocOpts struct {
13
14 BasePath string
15
16
17 Path string
18
19
20
21
22 SpecURL string
23
24
25 Title string
26
27
28 Template string
29
30
31
32
33 RapiDocURL string
34 }
35
36 func (r *RapiDocOpts) EnsureDefaults() {
37 common := toCommonUIOptions(r)
38 common.EnsureDefaults()
39 fromCommonToAnyOptions(common, r)
40
41
42 if r.RapiDocURL == "" {
43 r.RapiDocURL = rapidocLatest
44 }
45 if r.Template == "" {
46 r.Template = rapidocTemplate
47 }
48 }
49
50
51
52
53 func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler {
54 opts.EnsureDefaults()
55
56 pth := path.Join(opts.BasePath, opts.Path)
57 tmpl := template.Must(template.New("rapidoc").Parse(opts.Template))
58 assets := bytes.NewBuffer(nil)
59 if err := tmpl.Execute(assets, opts); err != nil {
60 panic(fmt.Errorf("cannot execute template: %w", err))
61 }
62
63 return serveUI(pth, assets.Bytes(), next)
64 }
65
66 const (
67 rapidocLatest = "https://unpkg.com/rapidoc/dist/rapidoc-min.js"
68 rapidocTemplate = `<!doctype html>
69 <html>
70 <head>
71 <title>{{ .Title }}</title>
72 <meta charset="utf-8"> <!-- Important: rapi-doc uses utf8 characters -->
73 <script type="module" src="{{ .RapiDocURL }}"></script>
74 </head>
75 <body>
76 <rapi-doc spec-url="{{ .SpecURL }}"></rapi-doc>
77 </body>
78 </html>
79 `
80 )
81
View as plain text