Skip to content

Commit ae1efd8

Browse files
author
wander
committed
fix global variable treeGroup is racy
修复treeGroup全局变量有数据竞争
1 parent f5bdf10 commit ae1efd8

File tree

2 files changed

+14
-19
lines changed

2 files changed

+14
-19
lines changed

pretree.go

Lines changed: 13 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -28,48 +28,44 @@ const (
2828
MethodTrace = "TRACE"
2929
)
3030

31-
var treeGroup map[string]*Tree
32-
33-
func init() {
34-
methods := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE"}
35-
treeGroup = make(map[string]*Tree)
36-
for _, method := range methods {
37-
tree := newTree()
38-
tree.name = string(method)
39-
treeGroup[method] = tree
40-
}
41-
}
42-
4331
type PreTree struct {
32+
treeGroup map[string]*Tree
4433
}
4534

4635
// 初始化对象
4736
//
4837
// Initialize object
4938
func NewPreTree() *PreTree {
50-
return &PreTree{}
39+
p := &PreTree{}
40+
methods := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE"}
41+
p.treeGroup = make(map[string]*Tree)
42+
for _, method := range methods {
43+
tree := newTree()
44+
tree.name = string(method)
45+
p.treeGroup[method] = tree
46+
}
47+
return p
5148
}
5249

5350
// 存储路由规则
5451
//
5552
// Store routing rules
5653
func (p *PreTree) Store(method, urlRule string) {
57-
t := treeGroup[method]
54+
t := p.treeGroup[method]
5855
t.insert(urlRule)
5956
}
6057

6158
// 查询URL匹配的树节点并返回变量
6259
//
6360
// Query the tree node with matching URL and return variables
64-
func (P *PreTree) Query(method, urlPath string) (isExist bool, rule string, vars map[string]string) {
65-
t := treeGroup[method]
61+
func (p *PreTree) Query(method, urlPath string) (isExist bool, rule string, vars map[string]string) {
62+
t := p.treeGroup[method]
6663
isExist, node, vars := t.match(urlPath)
6764
if isExist {
6865
return true, node.Rule(), vars
6966
} else {
7067
return false, "", vars
7168
}
72-
7369
}
7470

7571
// 前缀树数据结构

pretree_test.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,18 +43,17 @@ func Test_Match(t *testing.T) {
4343
{"POST", "/user", "/user"},
4444
}
4545

46+
p := pretree.NewPreTree()
4647
for _, v := range data {
4748
method := v[0]
4849
sourceRule := v[1]
49-
p := pretree.NewPreTree()
5050
p.Store(method, sourceRule)
5151
}
5252

5353
for _, v := range data {
5454
method := v[0]
5555
urlPath := v[2]
5656
sourceRule := v[1]
57-
p := pretree.NewPreTree()
5857
ok, rule, vars := p.Query(method, urlPath)
5958
if ok && rule == sourceRule {
6059
t.Logf("urlPath:%s match rule:%s result: %t vars: %s", urlPath, rule, ok, vars)

0 commit comments

Comments
 (0)