-
Notifications
You must be signed in to change notification settings - Fork 31
/
swagger.go
101 lines (83 loc) · 1.93 KB
/
swagger.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
package swagger
import (
"fmt"
"html/template"
"net/http"
"path"
"strings"
"sync"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gofiber/fiber/v2/utils"
swaggerFiles "github.com/swaggo/files/v2"
"github.com/swaggo/swag"
)
const (
defaultDocURL = "doc.json"
defaultIndex = "index.html"
)
var HandlerDefault = New()
// New returns custom handler
func New(config ...Config) fiber.Handler {
cfg := configDefault(config...)
index, err := template.New("swagger_index.html").Parse(indexTmpl)
if err != nil {
panic(fmt.Errorf("fiber: swagger middleware error -> %w", err))
}
var (
prefix string
once sync.Once
fs = filesystem.New(filesystem.Config{Root: http.FS(swaggerFiles.FS)})
)
return func(c *fiber.Ctx) error {
// Set prefix
once.Do(
func() {
prefix = strings.ReplaceAll(c.Route().Path, "*", "")
forwardedPrefix := getForwardedPrefix(c)
if forwardedPrefix != "" {
prefix = forwardedPrefix + prefix
}
// Set doc url
if len(cfg.URL) == 0 {
cfg.URL = path.Join(prefix, defaultDocURL)
}
},
)
p := c.Path(utils.CopyString(c.Params("*")))
switch p {
case defaultIndex:
c.Type("html")
return index.Execute(c, cfg)
case defaultDocURL:
var doc string
if doc, err = swag.ReadDoc(cfg.InstanceName); err != nil {
return err
}
return c.Type("json").SendString(doc)
case "", "/":
return c.Redirect(path.Join(prefix, defaultIndex), fiber.StatusMovedPermanently)
default:
return fs(c)
}
}
}
func getForwardedPrefix(c *fiber.Ctx) string {
header := c.GetReqHeaders()["X-Forwarded-Prefix"]
if len(header) == 0 {
return ""
}
prefix := ""
for _, rawPrefix := range header {
endIndex := len(rawPrefix)
for endIndex > 1 && rawPrefix[endIndex-1] == '/' {
endIndex--
}
if endIndex != len(rawPrefix) {
prefix += rawPrefix[:endIndex]
} else {
prefix += rawPrefix
}
}
return prefix
}