wrs *WebPath
}
-func NewSyncMap(conf *http.Server, m *WebPath) (o *WebSync) {
+func NewSyncMap(conf *http.Server, m *WebPath, matchFunc ...func(path string) (func(w http.ResponseWriter, r *http.Request), bool)) (o *WebSync) {
o = new(WebSync)
o.Server.Handler = o.mux
}
+ matchFunc = append(matchFunc, o.wrs.Load)
+
go o.Server.ListenAndServe()
o.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- f, ok := o.wrs.Load(r.URL.Path)
+ f, ok := matchFunc[0](r.URL.Path)
if ok {
f(w, r)
} else {
return t.sameP.Load(path)
}
if t.path[ltp-1] == '/' {
- return t.f, true
+ return t.f, t.f != nil
} else {
return nil, false
}
}
}
+func (t *WebPath) LoadPerfix(path string) (func(w http.ResponseWriter, r *http.Request), bool) {
+ t.RLock()
+ defer t.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] == '/') {
+ // 操作sameP节点
+ if t.sameP != nil {
+ if f, ok := t.sameP.LoadPerfix(path); ok {
+ return f, f != nil
+ }
+ }
+ if t.path[ltp-1] == '/' {
+ return t.f, t.f != nil
+ } else {
+ return nil, false
+ }
+ } else if lp < ltp && t.path[:lp] == path && (path[lp-1] == '/' || t.path[lp] == '/') {
+ // 操作sameP节点
+ return nil, false
+ } else {
+ // 操作next节点
+ if t.next != nil {
+ if f, ok := t.next.LoadPerfix(path); ok {
+ return f, f != nil
+ }
+ }
+ return nil, false
+ }
+}
+
func (t *WebPath) Store(path string, f func(w http.ResponseWriter, r *http.Request)) {
t.Lock()
defer t.Unlock()
}
}
+func Test_Server2(t *testing.T) {
+ var m WebPath
+ m.Store("/", func(w http.ResponseWriter, _ *http.Request) {
+ w.Write([]byte("/"))
+ })
+ m.Store("/1", func(w http.ResponseWriter, _ *http.Request) {
+ w.Write([]byte("/1"))
+ })
+ s := NewSyncMap(&http.Server{
+ Addr: "127.0.0.1:13001",
+ WriteTimeout: time.Millisecond,
+ }, &m, m.LoadPerfix)
+ defer s.Shutdown()
+
+ time.Sleep(time.Second)
+
+ r := reqf.New()
+ {
+ r.Reqf(reqf.Rval{
+ Url: "http://127.0.0.1:13001/1",
+ })
+ if !bytes.Equal(r.Respon, []byte("/1")) {
+ t.Fatal(r.Respon)
+ }
+ }
+ {
+ r.Reqf(reqf.Rval{
+ Url: "http://127.0.0.1:13001/2",
+ })
+ if !bytes.Equal(r.Respon, []byte("/")) {
+ t.Fatal(r.Respon)
+ }
+ }
+}
+
func Test_ServerSyncMap(t *testing.T) {
var m WebPath
m.Store("/", func(w http.ResponseWriter, _ *http.Request) {
if !bytes.Equal(r.Respon, []byte("{\"code\":0,\"message\":\"ok\",\"data\":{\"a\":\"0\",\"b\":[\"0\"],\"c\":{\"0\":1}}}")) {
t.Error(string(r.Respon))
}
+ r.Reqf(reqf.Rval{
+ Url: "http://127.0.0.1:13000/2",
+ })
+ if r.Response.StatusCode != 404 {
+ t.Error(string(r.Respon))
+ }
m.Store("/2/", nil)
r.Reqf(reqf.Rval{
Url: "http://127.0.0.1:13000/2/",