From b9a43d703ece8c8a63ef4e9823b9960e42acf1fe Mon Sep 17 00:00:00 2001 From: qydysky Date: Thu, 7 Mar 2024 15:31:33 +0800 Subject: [PATCH] 1 --- web/Web.go | 16 ++++++++-------- web/Web_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/web/Web.go b/web/Web.go index 5c581eb..bddad85 100644 --- a/web/Web.go +++ b/web/Web.go @@ -105,7 +105,7 @@ type WebPath struct { f func(w http.ResponseWriter, r *http.Request) sameP *WebPath next *WebPath - sync.RWMutex + l sync.RWMutex } // WebSync @@ -114,8 +114,8 @@ func (t *WebPath) GetConn(r *http.Request) net.Conn { } 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 @@ -142,12 +142,12 @@ func (t *WebPath) Load(path string) (func(w http.ResponseWriter, r *http.Request } 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 { @@ -174,8 +174,8 @@ func (t *WebPath) LoadPerfix(path string) (func(w http.ResponseWriter, r *http.R } 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 diff --git a/web/Web_test.go b/web/Web_test.go index 392f02a..d5f3c67 100644 --- a/web/Web_test.go +++ b/web/Web_test.go @@ -65,6 +65,39 @@ func Test_Server(t *testing.T) { } } +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) { -- 2.39.2