f func(w http.ResponseWriter, r *http.Request)
sameP *WebPath
next *WebPath
- sync.RWMutex
+ l sync.RWMutex
}
// WebSync
}
func (t *WebPath) Load(path string) (func(w http.ResponseWriter, r *http.Request), bool) {
- t.RLock()
- defer t.RUnlock()
+ t.l.RLock()
+ defer t.l.RUnlock()
if t.path == path {
// 操作本节点
return t.f, t.f != nil
}
func (t *WebPath) LoadPerfix(path string) (func(w http.ResponseWriter, r *http.Request), bool) {
- t.RLock()
- defer t.RUnlock()
+ t.l.RLock()
+ defer t.l.RUnlock()
if t.path == path {
// 操作本节点
return t.f, t.f != nil
- } else if lp, ltp := len(path), len(t.path); lp > ltp && path[:ltp] == t.path && (path[ltp] == '/' || t.path[ltp-1] == '/') {
+ } else if lp, ltp := len(path), len(t.path); lp > ltp && path[:ltp] == t.path && t.path[ltp-1] == '/' {
// 操作sameP节点
if t.sameP != nil {
if f, ok := t.sameP.LoadPerfix(path); ok {
}
func (t *WebPath) Store(path string, f func(w http.ResponseWriter, r *http.Request)) {
- t.Lock()
- defer t.Unlock()
+ t.l.Lock()
+ defer t.l.Unlock()
if t.path == path || (t.path == "" && t.f == nil) {
// 操作本节点
t.path = path
}
}
+func failIfNot[T comparable](t *testing.T, a, b T) {
+ t.Logf("a:'%v' b:'%v'", a, b)
+ if a != b {
+ t.Fail()
+ }
+}
+
+func Test_path(t *testing.T) {
+ var m WebPath
+ var res string
+ var f1 = func(_ http.ResponseWriter, _ *http.Request) { res += "f1" }
+ var f2 = func(_ http.ResponseWriter, _ *http.Request) { res += "f2" }
+ m.Store("/1", f2)
+ m.Store("/1/", f1)
+ failIfNot(t, res, "")
+ if sf1, ok := m.LoadPerfix("/1/"); ok {
+ sf1(nil, nil)
+ }
+ failIfNot(t, res, "f1")
+ if sf1, ok := m.LoadPerfix("/1"); ok {
+ sf1(nil, nil)
+ }
+ failIfNot(t, res, "f1f2")
+ if sf1, ok := m.LoadPerfix("/121"); ok {
+ sf1(nil, nil)
+ }
+ failIfNot(t, res, "f1f2")
+ if sf1, ok := m.LoadPerfix("/1/1"); ok {
+ sf1(nil, nil)
+ }
+ failIfNot(t, res, "f1f2f1")
+}
+
func Test_Server2(t *testing.T) {
var m WebPath
m.Store("/", func(w http.ResponseWriter, _ *http.Request) {