From 0aadbd7c4b6ae07351547db3c120cc02079c46d8 Mon Sep 17 00:00:00 2001 From: qydysky <32743305+qydysky@users.noreply.github.com> Date: Mon, 6 Feb 2023 21:51:47 +0800 Subject: [PATCH] Add ServerSync --- web/Web.go | 39 +++++++++++++++++++++++++++++++++++++++ web/Web_test.go | 20 +++++++++++++++++--- 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/web/Web.go b/web/Web.go index 608429e..b120f66 100644 --- a/web/Web.go +++ b/web/Web.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "strconv" + "sync" "time" sys "github.com/qydysky/part/sys" @@ -12,12 +13,15 @@ import ( type Web struct { Server *http.Server mux *http.ServeMux + wrs sync.Map + mode string } func New(conf *http.Server) (o *Web) { o = new(Web) + o.mode = "simple" o.Server = conf if o.Server.Handler == nil { @@ -30,12 +34,47 @@ func New(conf *http.Server) (o *Web) { return } +func NewSync(conf *http.Server) (o *Web) { + + o = new(Web) + + o.mode = "sync" + 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 := o.wrs.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创建的") + } for k, v := range path_func { t.mux.HandleFunc(k, v) } } +func (t *Web) HandleSync(path string, path_func func(http.ResponseWriter, *http.Request)) { + if t.mode != "sync" { + panic("必须是NewSync创建的") + } + t.wrs.Store(path, path_func) +} + func Easy_boot() *Web { s := New(&http.Server{ Addr: "127.0.0.1:" + strconv.Itoa(sys.Sys().GetFreePort()), diff --git a/web/Web_test.go b/web/Web_test.go index ec6f209..0d585e6 100644 --- a/web/Web_test.go +++ b/web/Web_test.go @@ -1,12 +1,26 @@ package part import ( + "net/http" + "strconv" "testing" "time" ) func Test_Server(t *testing.T) { s := Easy_boot() - t.Log(`http://`+s.Server.Addr) - time.Sleep(time.Second*time.Duration(100)) -} \ No newline at end of file + t.Log(`http://` + s.Server.Addr) + time.Sleep(time.Second * time.Duration(100)) +} + +func Test_ServerSync(t *testing.T) { + s := NewSync(&http.Server{ + Addr: "127.0.0.1:9090", + }) + for i := 0; i < 20; i++ { + time.Sleep(time.Second) + s.HandleSync("/1", func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(strconv.Itoa(i))) + }) + } +} -- 2.39.2