-
Notifications
You must be signed in to change notification settings - Fork 5
/
swagger_ui.go
66 lines (56 loc) · 1.52 KB
/
swagger_ui.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
64
65
66
package internal
import (
"bytes"
"fmt"
"os"
"path"
"strconv"
"text/template"
)
// SetupSwaggerUI sets url in the Swagger docs to the endpoint where specPath is served.
func SetupSwaggerUI(url string, specPath, swaggerUIDir string) error {
buf := &bytes.Buffer{}
t, err := template.New("").Parse(`
window.onload = function () {
//<editor-fold desc="Changeable Configuration Block">
window.ui = SwaggerUIBundle({
url: {{.URL}},
dom_id: "#swagger-ui",
deepLinking: true,
presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset],
plugins: [SwaggerUIBundle.plugins.DownloadUrl],
layout: "StandaloneLayout",
onComplete: function () {
const env = {{.Env}};
let spec = ui.specSelectors.specJson().toJS();
console.log(spec.servers)
let servers = spec.servers.filter((item) => {
return item["description"]?.toLowerCase() === env.toLowerCase();
});
spec.servers = servers;
ui.specActions.updateJsonSpec(spec);
},
});
//</editor-fold>
};
`)
if err != nil {
return err
}
params := map[string]interface{}{
"URL": strconv.Quote(url),
"Env": strconv.Quote(Config.AppEnv),
}
if err := t.Execute(buf, params); err != nil {
return err
}
swaggerInitPath := path.Join(swaggerUIDir, "swagger-initializer.js")
swaggerInit, err := os.Create(swaggerInitPath)
if err != nil {
return fmt.Errorf("could not create %s: %w", swaggerInitPath, err)
}
if _, err := swaggerInit.Write(buf.Bytes()); err != nil {
return fmt.Errorf("could not write to %s: %w", swaggerInitPath, err)
}
return nil
}