]> 127.0.0.1 Git - part/.git/commitdiff
Add NewSyncMap v0.22.1
authorqydysky <32743305+qydysky@users.noreply.github.com>
Mon, 6 Feb 2023 14:16:39 +0000 (22:16 +0800)
committerqydysky <32743305+qydysky@users.noreply.github.com>
Mon, 6 Feb 2023 14:16:39 +0000 (22:16 +0800)
web/Web.go
web/Web_test.go

index b120f66fb11b3bfaf61eca49bd7319b29f7d4f09..4831e55dbb5ade7f3c098644b65776cb84cf13f3 100644 (file)
@@ -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创建的")
index 0d585e6e5cca6391a9d30c7f6862dda59d549cee..a5a4cfe001c303cfc25b87f935b00d90842f6df1 100644 (file)
@@ -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)))
+               })
+       }
+}