-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserve.go
69 lines (60 loc) · 1.33 KB
/
serve.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
67
68
69
package openapi
import (
"bytes"
"encoding/json"
"text/template"
)
var scalarHTML = `
<!doctype html>
<html>
<head>
<title>API Reference</title>
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1" />
</head>
<body>
<script
id="api-reference"
type="application/json">
{{.Spec}}
</script>
<script>
var configuration = {{.Config}}
var apiReference = document.getElementById('api-reference')
apiReference.dataset.configuration = JSON.stringify(configuration)
</script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
</body>
</html>
`
// Scalar returns text/HTML for serving an OpenAPI spec using the scalar library.
func Scalar(openAPI *OpenAPI, configuration map[string]any) []byte {
scalar := template.New("scalar")
scalar, err := scalar.Parse(scalarHTML)
if err != nil {
panic(err)
}
buf := &bytes.Buffer{}
specJSON, err := json.Marshal(openAPI)
if err != nil {
panic(err)
}
configJSON, err := json.Marshal(configuration)
if err != nil {
panic(err)
}
type ScalarConfig struct {
Spec string
Config string
}
err = scalar.Execute(buf, &ScalarConfig{
Spec: string(specJSON),
Config: string(configJSON),
})
if err != nil {
panic(err)
}
return buf.Bytes()
}