Skip to content

Commit 5fc6d79

Browse files
committed
adds swagger ui as documentation option
Signed-off-by: Ivan Porto Carrero <[email protected]>
1 parent 095c1f4 commit 5fc6d79

File tree

3 files changed

+208
-0
lines changed

3 files changed

+208
-0
lines changed

middleware/context.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,6 +567,26 @@ func (c *Context) Respond(rw http.ResponseWriter, r *http.Request, produces []st
567567
c.api.ServeErrorFor(route.Operation.ID)(rw, r, errors.New(http.StatusInternalServerError, "can't produce response"))
568568
}
569569

570+
func (c *Context) APIHandlerSwaggerUI(builder Builder) http.Handler {
571+
b := builder
572+
if b == nil {
573+
b = PassthroughBuilder
574+
}
575+
576+
var title string
577+
sp := c.spec.Spec()
578+
if sp != nil && sp.Info != nil && sp.Info.Title != "" {
579+
title = sp.Info.Title
580+
}
581+
582+
swaggerUIOpts := SwaggerUIOpts{
583+
BasePath: c.BasePath(),
584+
Title: title,
585+
}
586+
587+
return Spec("", c.spec.Raw(), SwaggerUI(swaggerUIOpts, c.RoutesHandler(b)))
588+
}
589+
570590
// APIHandler returns a handler to serve the API, this includes a swagger spec, router and the contract defined in the swagger spec
571591
func (c *Context) APIHandler(builder Builder) http.Handler {
572592
b := builder

middleware/swaggerui.go

Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
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+
20+
// The three components needed to embed swagger-ui
21+
SwaggerURL string
22+
SwaggerPresetURL string
23+
SwaggerStylesURL string
24+
25+
Favicon32 string
26+
Favicon16 string
27+
28+
// Title for the documentation site, default to: API documentation
29+
Title string
30+
}
31+
32+
// EnsureDefaults in case some options are missing
33+
func (r *SwaggerUIOpts) EnsureDefaults() {
34+
if r.BasePath == "" {
35+
r.BasePath = "/"
36+
}
37+
if r.Path == "" {
38+
r.Path = "docs"
39+
}
40+
if r.SpecURL == "" {
41+
r.SpecURL = "/swagger.json"
42+
}
43+
if r.SwaggerURL == "" {
44+
r.SwaggerURL = swaggerLatest
45+
}
46+
if r.SwaggerPresetURL == "" {
47+
r.SwaggerPresetURL = swaggerPresetLatest
48+
}
49+
if r.SwaggerStylesURL == "" {
50+
r.SwaggerStylesURL = swaggerStylesLatest
51+
}
52+
if r.Favicon16 == "" {
53+
r.Favicon16 = swaggerFavicon16Latest
54+
}
55+
if r.Favicon32 == "" {
56+
r.Favicon32 = swaggerFavicon32Latest
57+
}
58+
if r.Title == "" {
59+
r.Title = "API documentation"
60+
}
61+
}
62+
63+
// SwaggerUI creates a middleware to serve a documentation site for a swagger spec.
64+
// This allows for altering the spec before starting the http listener.
65+
func SwaggerUI(opts SwaggerUIOpts, next http.Handler) http.Handler {
66+
opts.EnsureDefaults()
67+
68+
pth := path.Join(opts.BasePath, opts.Path)
69+
tmpl := template.Must(template.New("swaggerui").Parse(swaggeruiTemplate))
70+
71+
buf := bytes.NewBuffer(nil)
72+
_ = tmpl.Execute(buf, &opts)
73+
b := buf.Bytes()
74+
75+
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
76+
if r.URL.Path == pth {
77+
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
78+
rw.WriteHeader(http.StatusOK)
79+
80+
_, _ = rw.Write(b)
81+
return
82+
}
83+
84+
if next == nil {
85+
rw.Header().Set("Content-Type", "text/plain")
86+
rw.WriteHeader(http.StatusNotFound)
87+
_, _ = rw.Write([]byte(fmt.Sprintf("%q not found", pth)))
88+
return
89+
}
90+
next.ServeHTTP(rw, r)
91+
})
92+
}
93+
94+
const (
95+
swaggerLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"
96+
swaggerPresetLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui-standalone-preset.js"
97+
swaggerStylesLatest = "https://unpkg.com/swagger-ui-dist/swagger-ui.css"
98+
swaggerFavicon32Latest = "https://unpkg.com/swagger-ui-dist/favicon-32x32.png"
99+
swaggerFavicon16Latest = "https://unpkg.com/swagger-ui-dist/favicon-16x16.png"
100+
swaggeruiTemplate = `
101+
<!DOCTYPE html>
102+
<html lang="en">
103+
<head>
104+
<meta charset="UTF-8">
105+
<title>{{ .Title }}</title>
106+
107+
<link rel="stylesheet" type="text/css" href="{{ .SwaggerStylesURL }}" >
108+
<link rel="icon" type="image/png" href="{{ .Favicon32 }}" sizes="32x32" />
109+
<link rel="icon" type="image/png" href="{{ .Favicon16 }}" sizes="16x16" />
110+
<style>
111+
html
112+
{
113+
box-sizing: border-box;
114+
overflow: -moz-scrollbars-vertical;
115+
overflow-y: scroll;
116+
}
117+
118+
*,
119+
*:before,
120+
*:after
121+
{
122+
box-sizing: inherit;
123+
}
124+
125+
body
126+
{
127+
margin:0;
128+
background: #fafafa;
129+
}
130+
</style>
131+
</head>
132+
133+
<body>
134+
<div id="swagger-ui"></div>
135+
136+
<script src="{{ .SwaggerURL }}"> </script>
137+
<script src="{{ .SwaggerPresetURL }}"> </script>
138+
<script>
139+
window.onload = function() {
140+
// Begin Swagger UI call region
141+
const ui = SwaggerUIBundle({
142+
url: '{{ .SpecURL }}',
143+
dom_id: '#swagger-ui',
144+
deepLinking: true,
145+
presets: [
146+
SwaggerUIBundle.presets.apis,
147+
SwaggerUIStandalonePreset
148+
],
149+
plugins: [
150+
SwaggerUIBundle.plugins.DownloadUrl
151+
],
152+
layout: "StandaloneLayout"
153+
})
154+
// End Swagger UI call region
155+
156+
window.ui = ui
157+
}
158+
</script>
159+
</body>
160+
</html>
161+
`
162+
)

middleware/swaggerui_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package middleware
2+
3+
import (
4+
"net/http"
5+
"net/http/httptest"
6+
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
func TestSwaggerUIMiddleware(t *testing.T) {
12+
redoc := SwaggerUI(SwaggerUIOpts{}, nil)
13+
14+
req, _ := http.NewRequest("GET", "/docs", nil)
15+
recorder := httptest.NewRecorder()
16+
redoc.ServeHTTP(recorder, req)
17+
assert.Equal(t, 200, recorder.Code)
18+
assert.Equal(t, "text/html; charset=utf-8", recorder.Header().Get("Content-Type"))
19+
assert.Contains(t, recorder.Body.String(), "<title>API documentation</title>")
20+
assert.Contains(t, recorder.Body.String(), "url: '\\/swagger.json',")
21+
assert.Contains(t, recorder.Body.String(), swaggerLatest)
22+
assert.Contains(t, recorder.Body.String(), swaggerPresetLatest)
23+
assert.Contains(t, recorder.Body.String(), swaggerStylesLatest)
24+
assert.Contains(t, recorder.Body.String(), swaggerFavicon16Latest)
25+
assert.Contains(t, recorder.Body.String(), swaggerFavicon32Latest)
26+
}

0 commit comments

Comments
 (0)