This repository has been archived by the owner on Apr 20, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathswagger.go
66 lines (58 loc) · 1.38 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
package swagger
import (
"fmt"
"html/template"
"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"
"github.com/swaggo/swag"
)
// 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 fiber.Handler = filesystem.New(filesystem.Config{Root: swaggerFiles.HTTP})
)
return func(c *fiber.Ctx) error {
// Set prefix
once.Do(func() {
prefix = strings.ReplaceAll(c.Route().Path, "*", "")
// Set doc url
if len(cfg.URL) == 0 {
cfg.URL = path.Join(prefix, defaultDocURL)
}
})
var p string
if p = utils.ImmutableString(c.Params("*")); p != "" {
c.Path(p)
} else {
p = strings.TrimPrefix(c.Path(), prefix)
p = strings.TrimPrefix(p, "/")
}
switch p {
case defaultIndex:
c.Type("html")
return index.Execute(c, cfg)
case defaultDocURL:
doc, err := swag.ReadDoc()
if err != nil {
return err
}
return c.Type("json").SendString(doc)
case "", "/":
return c.Redirect(path.Join(prefix, defaultIndex), fiber.StatusMovedPermanently)
default:
return fs(c)
}
}
}