-
Notifications
You must be signed in to change notification settings - Fork 5
/
utils.go
68 lines (54 loc) · 1.61 KB
/
utils.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
package fiber
import (
"regexp"
"strings"
"github.com/gofiber/fiber/v2"
httpcontract "github.com/goravel/framework/contracts/http"
)
func pathToFiberPath(relativePath string) string {
return bracketToColon(mergeSlashForPath(relativePath))
}
func middlewaresToFiberHandlers(middlewares []httpcontract.Middleware) []fiber.Handler {
var fiberHandlers []fiber.Handler
for _, item := range middlewares {
fiberHandlers = append(fiberHandlers, middlewareToFiberHandler(item))
}
return fiberHandlers
}
func handlerToFiberHandler(handler httpcontract.HandlerFunc) fiber.Handler {
return func(ctx *fiber.Ctx) error {
if response := handler(NewContext(ctx)); response != nil {
return response.Render()
}
return nil
}
}
func middlewareToFiberHandler(middleware httpcontract.Middleware) fiber.Handler {
return func(ctx *fiber.Ctx) error {
middleware(NewContext(ctx))
return nil
}
}
func colonToBracket(relativePath string) string {
arr := strings.Split(relativePath, "/")
var newArr []string
for _, item := range arr {
if strings.HasPrefix(item, ":") {
item = "{" + strings.ReplaceAll(item, ":", "") + "}"
}
newArr = append(newArr, item)
}
return strings.Join(newArr, "/")
}
func bracketToColon(relativePath string) string {
compileRegex := regexp.MustCompile(`{(.*?)}`)
matchArr := compileRegex.FindAllStringSubmatch(relativePath, -1)
for _, item := range matchArr {
relativePath = strings.ReplaceAll(relativePath, item[0], ":"+item[1])
}
return relativePath
}
func mergeSlashForPath(path string) string {
path = strings.ReplaceAll(path, "//", "/")
return strings.ReplaceAll(path, "//", "/")
}