forked from swaggo/swag
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spec.go
64 lines (53 loc) · 1.43 KB
/
spec.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
package swag
import (
"bytes"
"encoding/json"
"strings"
"text/template"
)
// Spec holds exported Swagger Info so clients can modify it.
type Spec struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
InfoInstanceName string
SwaggerTemplate string
LeftDelim string
RightDelim string
}
// ReadDoc parses SwaggerTemplate into swagger document.
func (i *Spec) ReadDoc() string {
i.Description = strings.ReplaceAll(i.Description, "\n", "\\n")
tpl := template.New("swagger_info").Funcs(template.FuncMap{
"marshal": func(v interface{}) string {
a, _ := json.Marshal(v)
return string(a)
},
"escape": func(v interface{}) string {
// escape tabs
var str = strings.ReplaceAll(v.(string), "\t", "\\t")
// replace " with \", and if that results in \\", replace that with \\\"
str = strings.ReplaceAll(str, "\"", "\\\"")
return strings.ReplaceAll(str, "\\\\\"", "\\\\\\\"")
},
})
if i.LeftDelim != "" && i.RightDelim != "" {
tpl = tpl.Delims(i.LeftDelim, i.RightDelim)
}
parsed, err := tpl.Parse(i.SwaggerTemplate)
if err != nil {
return i.SwaggerTemplate
}
var doc bytes.Buffer
if err = parsed.Execute(&doc, i); err != nil {
return i.SwaggerTemplate
}
return doc.String()
}
// InstanceName returns Spec instance name.
func (i *Spec) InstanceName() string {
return i.InfoInstanceName
}