-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
127 lines (111 loc) · 2.46 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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package koa
import (
"bytes"
"net"
"runtime"
"strconv"
"strings"
)
// compare path middleware prefix, target request path
func compare(path string, target string) bool {
if len(path) == 0 || path == "*" || path == "/*" {
return true
}
pathArr := strings.Split(path, "/")
targetArr := strings.Split(target, "/")
pathLen := len(pathArr)
targetLen := len(targetArr)
if pathLen <= targetLen {
for i, val := range pathArr {
if val == "*" {
return true
} else if val != targetArr[i] {
if strings.HasPrefix(val, ":") {
continue
} else {
return false
}
}
}
if pathLen == targetLen {
return true
}
}
return false
}
func compose(handles []Handle) Handler {
return func(ctx *Context, n Next) {
_curr := int32(0)
_max := len(handles)
var _next Next
_next = func() {
_ctx := ctx
_handles := handles
if int(_curr) < _max {
_currHandler := _handles[_curr]
_curr += 1
if (_currHandler.method == USE || _currHandler.method == ctx.Method) &&
compare(_currHandler.path, ctx.Path) {
ctx.Params = formatParams(_currHandler.path, ctx.Path)
_currHandler.handler(_ctx, _next)
} else {
_next()
}
} else {
ctx.Status = 404
}
}
_next()
}
}
func formatQuery(values map[string]([]string)) map[string]interface{} {
result := make(map[string]interface{})
for key, data := range values {
if strings.HasSuffix(key, "[]") {
key = strings.Replace(key, "[]", "", -1)
result[key] = data
} else {
result[key] = data[0]
}
}
return result
}
func formatParams(path string, target string) map[string]string {
result := make(map[string]string)
pathArr := strings.Split(path, "/")
targetArr := strings.Split(target, "/")
for idx, val := range pathArr {
if !strings.HasPrefix(val, ":") {
continue
}
if val != targetArr[idx] {
variable := strings.TrimPrefix(val, ":")
result[variable] = targetArr[idx]
}
}
return result
}
// GetLocalAddrIp func
func GetLocalAddrIp() string {
ret := ""
addrs, err := net.InterfaceAddrs()
if err == nil {
for _, value := range addrs {
if ipnet, ok := value.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
ret += ipnet.IP.String()
}
}
}
}
return ret
}
// GetGoroutineID func
func GetGoroutineID() uint64 {
b := make([]byte, 64)
runtime.Stack(b, false)
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}