-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper.go
98 lines (82 loc) · 1.79 KB
/
helper.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
// go-rs/rest-api-framework
// Copyright(c) 2019-2022 Roshan Gade. All rights reserved.
// MIT Licensed
package rest
import (
"encoding/json"
"encoding/xml"
"fmt"
"regexp"
"strings"
)
type pattern struct {
value string
regexp *regexp.Regexp
keys []string
}
const sep = "/"
// compile the pattern
func (p *pattern) compile() error {
var err error
pattern := ""
p.keys = make([]string, 0)
for _, val := range strings.Split(p.value, "/") {
if val != "" {
switch val[0] {
case 94:
pattern += "(?:/(.*))"
case 42:
pattern += "(?:/(.*))"
p.keys = append(p.keys, "*")
case 58:
length := len(val)
lastChar := val[length-1]
if lastChar == 63 {
pattern += "(?:/([^/]+?))?"
p.keys = append(p.keys, val[1:(length-1)])
} else {
pattern += sep + "([^/]+?)"
p.keys = append(p.keys, val[1:])
}
default:
pattern += sep + val
}
}
}
p.regexp, err = regexp.Compile("^" + pattern + "/?$")
return err
}
// match request URI with pattern
func (p *pattern) test(str string) bool {
return p.regexp.MatchString(str)
}
// on URL path match, map every keys with pattern values
func (p *pattern) match(url string) map[string]string {
if len(p.keys) == 0 {
return nil
}
params := make(map[string]string)
matches := p.regexp.FindAllSubmatch([]byte(url), -1)
for i, k := range matches[0][1:] {
params[p.keys[i]] = string(k)
if p.keys[i] == "*" {
params["*"] = sep + params["*"]
}
}
fmt.Println(params)
return params
}
// trim "/" from suffix
func trim(str string) string {
if strings.HasSuffix(str, sep) {
str = str[:len(str)-1]
}
return str
}
func jsonToBytes(data any) ([]byte, error) {
//standard JSON as per RFC 7159
return json.Marshal(data)
}
func xmlToBytes(data any) ([]byte, error) {
return xml.Marshal(data)
}