-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscalar.go
105 lines (90 loc) · 1.96 KB
/
scalar.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package scalar
import (
"encoding/json"
"fmt"
"os"
"strings"
)
const (
DefaultTitle = "Scalar API Reference"
DefaultCDN = "https://cdn.jsdelivr.net/npm/@scalar/api-reference"
)
type Scalar struct {
title string
cdn string
customCSS string
config string
content string
}
// New creates a new instance of the Scalar API reference
func New(specURL string, cfg *Config) (*Scalar, error) {
if specURL == "" {
return nil, fmt.Errorf("spec URL or content is required")
}
type Spec struct {
URL string `json:"url"`
}
var spec *Spec
var content string
if strings.HasPrefix(specURL, "http") {
spec = &Spec{URL: specURL}
} else {
data, err := os.ReadFile(specURL)
if err != nil {
return nil, err
}
content = string(data)
}
title := cfg.Title
if title == "" {
title = DefaultTitle
}
cdn := cfg.CDN
if cdn == "" {
cdn = DefaultCDN
}
customCSS := cfg.CustomCSS
if cfg.Theme != "" {
customCSS = ""
}
// Serialize the configuration
data, err := json.Marshal(struct {
*Config
Spec *Spec `json:"spec,omitempty"`
}{
Config: cfg,
Spec: spec,
})
if err != nil {
return nil, err
}
// Replace double quotes with HTML entity
config := strings.ReplaceAll(string(data), `"`, `"`)
return &Scalar{
title: title,
cdn: cdn,
customCSS: customCSS,
config: config,
content: content,
}, nil
}
// RenderHTML renders the HTML content for the API reference
func (s *Scalar) RenderHTML() (string, error) {
htmlContent := fmt.Sprintf(`
<!DOCTYPE html>
<html lang="en">
<head>
<title>%s</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>%s</style>
</head>
<body>
<script id="api-reference" type="application/json" data-configuration="%s">%s</script>
<script src="%s"></script>
</body>
</html>
`, s.title, s.customCSS, s.config, s.content, s.cdn,
)
return htmlContent, nil
}