forked from ebhomengo/niki
1
0
Fork 0
niki/vendor/github.com/swaggo/swag/spec.go

98 lines
1.4 KiB
Go
Raw Normal View History

2024-05-14 13:07:09 +00:00
package swag
import (
"bytes"
"encoding/json"
"strings"
"text/template"
)
// Spec holds exported Swagger Info so clients can modify it.
2024-05-14 13:07:09 +00:00
type Spec struct {
Version string
Host string
BasePath string
Schemes []string
Title string
Description string
2024-05-14 13:07:09 +00:00
InfoInstanceName string
SwaggerTemplate string
LeftDelim string
RightDelim string
2024-05-14 13:07:09 +00:00
}
// ReadDoc parses SwaggerTemplate into swagger document.
2024-05-14 13:07:09 +00:00
func (i *Spec) ReadDoc() string {
2024-05-14 13:07:09 +00:00
i.Description = strings.ReplaceAll(i.Description, "\n", "\\n")
tpl := template.New("swagger_info").Funcs(template.FuncMap{
2024-05-14 13:07:09 +00:00
"marshal": func(v interface{}) string {
2024-05-14 13:07:09 +00:00
a, _ := json.Marshal(v)
return string(a)
2024-05-14 13:07:09 +00:00
},
2024-05-14 13:07:09 +00:00
"escape": func(v interface{}) string {
2024-05-14 13:07:09 +00:00
// escape tabs
2024-05-14 13:07:09 +00:00
var str = strings.ReplaceAll(v.(string), "\t", "\\t")
2024-05-14 13:07:09 +00:00
// replace " with \", and if that results in \\", replace that with \\\"
2024-05-14 13:07:09 +00:00
str = strings.ReplaceAll(str, "\"", "\\\"")
return strings.ReplaceAll(str, "\\\\\"", "\\\\\\\"")
2024-05-14 13:07:09 +00:00
},
})
if i.LeftDelim != "" && i.RightDelim != "" {
2024-05-14 13:07:09 +00:00
tpl = tpl.Delims(i.LeftDelim, i.RightDelim)
2024-05-14 13:07:09 +00:00
}
parsed, err := tpl.Parse(i.SwaggerTemplate)
2024-05-14 13:07:09 +00:00
if err != nil {
2024-05-14 13:07:09 +00:00
return i.SwaggerTemplate
2024-05-14 13:07:09 +00:00
}
var doc bytes.Buffer
2024-05-14 13:07:09 +00:00
if err = parsed.Execute(&doc, i); err != nil {
2024-05-14 13:07:09 +00:00
return i.SwaggerTemplate
2024-05-14 13:07:09 +00:00
}
return doc.String()
2024-05-14 13:07:09 +00:00
}
// InstanceName returns Spec instance name.
2024-05-14 13:07:09 +00:00
func (i *Spec) InstanceName() string {
2024-05-14 13:07:09 +00:00
return i.InfoInstanceName
2024-05-14 13:07:09 +00:00
}