podman

Форк
0
168 строк · 4.1 Кб
1
package middleware
2

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

11
// SwaggerUIOpts configures the Swaggerui middlewares
12
type SwaggerUIOpts 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
	// OAuthCallbackURL the url called after OAuth2 login
20
	OAuthCallbackURL string
21

22
	// The three components needed to embed swagger-ui
23
	SwaggerURL       string
24
	SwaggerPresetURL string
25
	SwaggerStylesURL string
26

27
	Favicon32 string
28
	Favicon16 string
29

30
	// Title for the documentation site, default to: API documentation
31
	Title string
32
}
33

34
// EnsureDefaults in case some options are missing
35
func (r *SwaggerUIOpts) EnsureDefaults() {
36
	if r.BasePath == "" {
37
		r.BasePath = "/"
38
	}
39
	if r.Path == "" {
40
		r.Path = "docs"
41
	}
42
	if r.SpecURL == "" {
43
		r.SpecURL = "/swagger.json"
44
	}
45
	if r.OAuthCallbackURL == "" {
46
		r.OAuthCallbackURL = path.Join(r.BasePath, r.Path, "oauth2-callback")
47
	}
48
	if r.SwaggerURL == "" {
49
		r.SwaggerURL = swaggerLatest
50
	}
51
	if r.SwaggerPresetURL == "" {
52
		r.SwaggerPresetURL = swaggerPresetLatest
53
	}
54
	if r.SwaggerStylesURL == "" {
55
		r.SwaggerStylesURL = swaggerStylesLatest
56
	}
57
	if r.Favicon16 == "" {
58
		r.Favicon16 = swaggerFavicon16Latest
59
	}
60
	if r.Favicon32 == "" {
61
		r.Favicon32 = swaggerFavicon32Latest
62
	}
63
	if r.Title == "" {
64
		r.Title = "API documentation"
65
	}
66
}
67

68
// SwaggerUI creates a middleware to serve a documentation site for a swagger spec.
69
// This allows for altering the spec before starting the http listener.
70
func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler {
71
	opts.EnsureDefaults()
72

73
	pth := path.Join(opts.BasePath, opts.Path)
74
	tmpl := template.Must(template.New("swaggerui").Parse(swaggeruiTemplate))
75

76
	buf := bytes.NewBuffer(nil)
77
	_ = tmpl.Execute(buf, &opts)
78
	b := buf.Bytes()
79

80
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
81
		if path.Join(r.URL.Path) == pth {
82
			rw.Header().Set("Content-Type", "text/html; charset=utf-8")
83
			rw.WriteHeader(http.StatusOK)
84

85
			_, _ = rw.Write(b)
86
			return
87
		}
88

89
		if next == nil {
90
			rw.Header().Set("Content-Type", "text/plain")
91
			rw.WriteHeader(http.StatusNotFound)
92
			_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
93
			return
94
		}
95
		next.ServeHTTP(rw, r)
96
	})
97
}
98

99
const (
100
	swaggerLatest          = "https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"
101
	swaggerPresetLatest    = "https://unpkg.com/swagger-ui-dist/swagger-ui-standalone-preset.js"
102
	swaggerStylesLatest    = "https://unpkg.com/swagger-ui-dist/swagger-ui.css"
103
	swaggerFavicon32Latest = "https://unpkg.com/swagger-ui-dist/favicon-32x32.png"
104
	swaggerFavicon16Latest = "https://unpkg.com/swagger-ui-dist/favicon-16x16.png"
105
	swaggeruiTemplate      = `
106
<!DOCTYPE html>
107
<html lang="en">
108
  <head>
109
    <meta charset="UTF-8">
110
		<title>{{ .Title }}</title>
111

112
    <link rel="stylesheet" type="text/css" href="{{ .SwaggerStylesURL }}" >
113
    <link rel="icon" type="image/png" href="{{ .Favicon32 }}" sizes="32x32" />
114
    <link rel="icon" type="image/png" href="{{ .Favicon16 }}" sizes="16x16" />
115
    <style>
116
      html
117
      {
118
        box-sizing: border-box;
119
        overflow: -moz-scrollbars-vertical;
120
        overflow-y: scroll;
121
      }
122

123
      *,
124
      *:before,
125
      *:after
126
      {
127
        box-sizing: inherit;
128
      }
129

130
      body
131
      {
132
        margin:0;
133
        background: #fafafa;
134
      }
135
    </style>
136
  </head>
137

138
  <body>
139
    <div id="swagger-ui"></div>
140

141
    <script src="{{ .SwaggerURL }}"> </script>
142
    <script src="{{ .SwaggerPresetURL }}"> </script>
143
    <script>
144
    window.onload = function() {
145
      // Begin Swagger UI call region
146
      const ui = SwaggerUIBundle({
147
        url: '{{ .SpecURL }}',
148
        dom_id: '#swagger-ui',
149
        deepLinking: true,
150
        presets: [
151
          SwaggerUIBundle.presets.apis,
152
          SwaggerUIStandalonePreset
153
        ],
154
        plugins: [
155
          SwaggerUIBundle.plugins.DownloadUrl
156
        ],
157
        layout: "StandaloneLayout",
158
		oauth2RedirectUrl: '{{ .OAuthCallbackURL }}'
159
      })
160
      // End Swagger UI call region
161

162
      window.ui = ui
163
    }
164
  </script>
165
  </body>
166
</html>
167
`
168
)
169

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

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

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

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