Skip to content

Commit

Permalink
fix global variable treeGroup is racy
Browse files Browse the repository at this point in the history
修复treeGroup全局变量有数据竞争
  • Loading branch information
wander committed Aug 24, 2021
1 parent f5bdf10 commit ae1efd8
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 19 deletions.
30 changes: 13 additions & 17 deletions pretree.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,48 +28,44 @@ const (
MethodTrace = "TRACE"
)

var treeGroup map[string]*Tree

func init() {
methods := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE"}
treeGroup = make(map[string]*Tree)
for _, method := range methods {
tree := newTree()
tree.name = string(method)
treeGroup[method] = tree
}
}

type PreTree struct {
treeGroup map[string]*Tree
}

// 初始化对象
//
// Initialize object
func NewPreTree() *PreTree {
return &PreTree{}
p := &PreTree{}
methods := []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE"}
p.treeGroup = make(map[string]*Tree)
for _, method := range methods {
tree := newTree()
tree.name = string(method)
p.treeGroup[method] = tree
}
return p
}

// 存储路由规则
//
// Store routing rules
func (p *PreTree) Store(method, urlRule string) {
t := treeGroup[method]
t := p.treeGroup[method]
t.insert(urlRule)
}

// 查询URL匹配的树节点并返回变量
//
// Query the tree node with matching URL and return variables
func (P *PreTree) Query(method, urlPath string) (isExist bool, rule string, vars map[string]string) {
t := treeGroup[method]
func (p *PreTree) Query(method, urlPath string) (isExist bool, rule string, vars map[string]string) {
t := p.treeGroup[method]
isExist, node, vars := t.match(urlPath)
if isExist {
return true, node.Rule(), vars
} else {
return false, "", vars
}

}

// 前缀树数据结构
Expand Down
3 changes: 1 addition & 2 deletions pretree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,17 @@ func Test_Match(t *testing.T) {
{"POST", "/user", "/user"},
}

p := pretree.NewPreTree()
for _, v := range data {
method := v[0]
sourceRule := v[1]
p := pretree.NewPreTree()
p.Store(method, sourceRule)
}

for _, v := range data {
method := v[0]
urlPath := v[2]
sourceRule := v[1]
p := pretree.NewPreTree()
ok, rule, vars := p.Query(method, urlPath)
if ok && rule == sourceRule {
t.Logf("urlPath:%s match rule:%s result: %t vars: %s", urlPath, rule, ok, vars)
Expand Down

0 comments on commit ae1efd8

Please sign in to comment.