swagui/swagui.go
jolheiser afd7d41140
Initial Commit
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-10-02 14:09:22 -05:00

77 lines
1.4 KiB
Go

package swagui
import (
"html/template"
"net/http"
"os"
"strings"
)
var (
defTitle = "Swagger API"
defScript = `const ui = SwaggerUIBundle({
url: "${specURL}",
dom_id: '#swagger-ui',
deepLinking: true,
docExpansion: "none",
presets: [
SwaggerUIBundle.presets.apis
]
});`
)
// SwagUI is a Swagger UI handler
type SwagUI struct {
specURL string
Title string
Script template.JS
}
// New returns a new SwagUI handler
func New(specURL string, opts ...Option) *SwagUI {
s := &SwagUI{
specURL: specURL,
Title: defTitle,
Script: expand(specURL, defScript),
}
for _, opt := range opts {
opt(s)
}
return s
}
// Option is a func for changing the default behavior of SwagUI
type Option func(*SwagUI)
// WithTitle allows setting a custom <title>
func WithTitle(title string) func(*SwagUI) {
return func(ui *SwagUI) {
ui.Title = title
}
}
// WithScript allows setting the <script> portion of Swagger UI
//
// NOTE: In your script you can use ${SpecURL} which will be replaced
// by the SwagUI specURL
func WithScript(script string) func(*SwagUI) {
return func(ui *SwagUI) {
ui.Script = expand(ui.specURL, script)
}
}
func (ui *SwagUI) ServeHTTP(w http.ResponseWriter, _ *http.Request) {
_ = tmpl.Execute(w, ui)
}
func expand(specURL, script string) template.JS {
return template.JS(os.Expand(script, func(s string) string {
if strings.EqualFold(s, "specURL") {
return specURL
}
return ""
}))
}