podman

Форк
0
90 строк · 2.2 Кб
1
package middleware
2

3
import (
4
	"bytes"
5
	"fmt"
6
	"html/template"
7
	"net/http"
8
	"path"
9
)
10

11
// RapiDocOpts configures the RapiDoc middlewares
12
type RapiDocOpts struct {
13
	// BasePath for the UI path, defaults to: /
14
	BasePath string
15
	// Path combines with BasePath for the full UI path, defaults to: docs
16
	Path string
17
	// SpecURL the url to find the spec for
18
	SpecURL string
19
	// RapiDocURL for the js that generates the rapidoc site, defaults to: https://cdn.jsdelivr.net/npm/rapidoc/bundles/rapidoc.standalone.js
20
	RapiDocURL string
21
	// Title for the documentation site, default to: API documentation
22
	Title string
23
}
24

25
// EnsureDefaults in case some options are missing
26
func (r *RapiDocOpts) EnsureDefaults() {
27
	if r.BasePath == "" {
28
		r.BasePath = "/"
29
	}
30
	if r.Path == "" {
31
		r.Path = "docs"
32
	}
33
	if r.SpecURL == "" {
34
		r.SpecURL = "/swagger.json"
35
	}
36
	if r.RapiDocURL == "" {
37
		r.RapiDocURL = rapidocLatest
38
	}
39
	if r.Title == "" {
40
		r.Title = "API documentation"
41
	}
42
}
43

44
// RapiDoc creates a middleware to serve a documentation site for a swagger spec.
45
// This allows for altering the spec before starting the http listener.
46
//
47
func RapiDoc(opts RapiDocOpts, next http.Handler) http.Handler {
48
	opts.EnsureDefaults()
49

50
	pth := path.Join(opts.BasePath, opts.Path)
51
	tmpl := template.Must(template.New("rapidoc").Parse(rapidocTemplate))
52

53
	buf := bytes.NewBuffer(nil)
54
	_ = tmpl.Execute(buf, opts)
55
	b := buf.Bytes()
56

57
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
58
		if r.URL.Path == pth {
59
			rw.Header().Set("Content-Type", "text/html; charset=utf-8")
60
			rw.WriteHeader(http.StatusOK)
61

62
			_, _ = rw.Write(b)
63
			return
64
		}
65

66
		if next == nil {
67
			rw.Header().Set("Content-Type", "text/plain")
68
			rw.WriteHeader(http.StatusNotFound)
69
			_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
70
			return
71
		}
72
		next.ServeHTTP(rw, r)
73
	})
74
}
75

76
const (
77
	rapidocLatest   = "https://unpkg.com/rapidoc/dist/rapidoc-min.js"
78
	rapidocTemplate = `<!doctype html>
79
<html>
80
<head>
81
  <title>{{ .Title }}</title>
82
  <meta charset="utf-8"> <!-- Important: rapi-doc uses utf8 charecters -->
83
  <script type="module" src="{{ .RapiDocURL }}"></script>
84
</head>
85
<body>
86
  <rapi-doc spec-url="{{ .SpecURL }}"></rapi-doc>
87
</body>
88
</html>
89
`
90
)
91

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.