-
Notifications
You must be signed in to change notification settings - Fork 0
/
internal.go
135 lines (116 loc) · 2.48 KB
/
internal.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
128
129
130
131
132
133
134
135
package gorouter
import (
"context"
"fmt"
"net/http"
"net/url"
"strings"
)
// toCtx transfer response, request and variables (optional) to ctx pass it into handle function
func toCtx(w http.ResponseWriter, r *http.Request, v ...Vars) *Ctx {
c := &Ctx{
Request: r,
Response: w,
}
if len(v) > 0 {
c.Vars = v[0]
}
return c
}
// handlePath handles path and return path elements and path variables
func handlePath(path string) ([]string, map[int]string) {
pathElems := make([]string, 0)
paramsValue := make(map[int]string)
if path[0] == '/' {
path = path[1:]
}
s := strings.Split(path, "/")
for i := range s {
if strings.Contains(s[i], "{") && strings.Contains(s[i], "}") {
param := fmt.Sprintf("%s", string(s[i][1:len(s[i])-1]))
paramsValue[i+1] = param
} else {
pathElems = append(pathElems, s[i])
}
}
return pathElems, paramsValue
}
// parseVars parses variables {var} and write them into map
func parseVars(u *url.URL, params map[int]string) map[string]string {
if len(params) < 1 {
return nil
}
path := u.Path
if path[0] == '/' {
path = path[1:]
}
s := strings.Split(path, "/")
vars := make(map[string]string)
for k, v := range params {
vars[v] = s[k-1]
}
return vars
}
// findPath finds a path, which is mostly like the one that was provided in a handlers map.
func findPath(r *http.Request, h map[string]HandlerStruct) (HandlerStruct, Vars, bool) {
path := r.URL.Path
if path[0] == '/' {
path = path[1:]
}
doneCh := make(chan struct{}, len(h))
foundCh := make(chan struct {
h HandlerStruct
v Vars
}, 1)
defer func() {
close(doneCh)
close(foundCh)
}()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
for _, handler := range h {
go func(ctx context.Context, h HandlerStruct) {
if len(h.vars) < 1 {
select {
case <-ctx.Done():
default:
doneCh <- struct{}{}
}
return
}
for _, elements := range handler.elems {
if !strings.Contains(path, elements) {
select {
case <-ctx.Done():
default:
doneCh <- struct{}{}
}
return
}
}
vars := parseVars(&url.URL{Path: path}, h.vars)
select {
case <-ctx.Done():
default:
foundCh <- struct {
h HandlerStruct
v Vars
}{h: h, v: vars}
}
}(ctx, handler)
}
doneCounter := 0
for {
select {
case f := <-foundCh:
cancel()
return f.h, f.v, true
case <-doneCh:
doneCounter++
if doneCounter == len(h) {
cancel()
return HandlerStruct{}, nil, false
}
}
}
}