From: qydysky <32743305+qydysky@users.noreply.github.com> Date: Mon, 6 Feb 2023 14:16:39 +0000 (+0800) Subject: Add NewSyncMap X-Git-Tag: v0.22.1 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=6df8deb213fdbf5bd4e34f5e30ab2b0048f2fcaf;p=part%2F.git Add NewSyncMap --- diff --git a/web/Web.go b/web/Web.go index b120f66..4831e55 100644 --- a/web/Web.go +++ b/web/Web.go @@ -59,6 +59,31 @@ func NewSync(conf *http.Server) (o *Web) { return } +func NewSyncMap(conf *http.Server, m *sync.Map) (o *Web) { + + o = new(Web) + + o.mode = "syncmap" + o.Server = conf + + if o.Server.Handler == nil { + o.mux = http.NewServeMux() + o.Server.Handler = o.mux + } + + go o.Server.ListenAndServe() + + o.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + if wr, ok := m.Load(r.URL.Path); ok { + if f, ok := wr.(func(http.ResponseWriter, *http.Request)); ok { + f(w, r) + } + } + }) + + return +} + func (t *Web) Handle(path_func map[string]func(http.ResponseWriter, *http.Request)) { if t.mode != "simple" { panic("必须是New创建的") diff --git a/web/Web_test.go b/web/Web_test.go index 0d585e6..a5a4cfe 100644 --- a/web/Web_test.go +++ b/web/Web_test.go @@ -3,6 +3,7 @@ package part import ( "net/http" "strconv" + "sync" "testing" "time" ) @@ -24,3 +25,19 @@ func Test_ServerSync(t *testing.T) { }) } } + +func Test_ServerSyncMap(t *testing.T) { + var m sync.Map + m.Store("/", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("1")) + }) + NewSyncMap(&http.Server{ + Addr: "127.0.0.1:9090", + }, &m) + for i := 0; i < 20; i++ { + time.Sleep(time.Second) + m.Store("/", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(strconv.Itoa(i))) + }) + } +}