From be9f9b2781232044a1e41c598fcce845d5b713a2 Mon Sep 17 00:00:00 2001 From: Pal Sivertsen Date: Thu, 22 Jun 2017 14:40:30 +0200 Subject: [PATCH] Root path support for ServeMux --- message.go | 4 ++++ servmux.go | 6 +++--- servmux_test.go | 13 ++++++++++++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/message.go b/message.go index 630ad2f..dab7aae 100644 --- a/message.go +++ b/message.go @@ -393,6 +393,10 @@ func (m Message) PathString() string { // SetPathString sets a path by a / separated string. func (m *Message) SetPathString(s string) { + if s == "/" || s == "" { + m.SetPath([]string{""}) + return + } for s[0] == '/' { s = s[1:] } diff --git a/servmux.go b/servmux.go index 23132f1..5864486 100644 --- a/servmux.go +++ b/servmux.go @@ -21,6 +21,9 @@ func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]muxEntry)} } // Does path match pattern? func pathMatch(pattern, path string) bool { if len(pattern) == 0 { + if pattern == path { + return true + } // should not happen return false } @@ -77,9 +80,6 @@ func (mux *ServeMux) Handle(pattern string, handler Handler) { pattern = pattern[1:] } - if pattern == "" { - panic("http: invalid pattern " + pattern) - } if handler == nil { panic("http: nil handler") } diff --git a/servmux_test.go b/servmux_test.go index b9ddc41..b9e97d8 100644 --- a/servmux_test.go +++ b/servmux_test.go @@ -18,6 +18,10 @@ func TestPathMatching(t *testing.T) { msgs["b"]++ return nil }) + m.HandleFunc("/", func(l *net.UDPConn, a *net.UDPAddr, m *Message) *Message { + msgs[""]++ + return nil + }) msg := &Message{} msg.SetPathString("/a") @@ -31,6 +35,9 @@ func TestPathMatching(t *testing.T) { msg.Type = NonConfirmable msg.SetPathString("/c") m.ServeCOAP(nil, nil, msg) + msg.SetPathString("/") + m.ServeCOAP(nil, nil, msg) + m.ServeCOAP(nil, nil, msg) if msgs["a"] != 2 { t.Errorf("Expected 2 messages for /a, got %v", msgs["a"]) @@ -38,6 +45,9 @@ func TestPathMatching(t *testing.T) { if msgs["b"] != 1 { t.Errorf("Expected 1 message for /b, got %v", msgs["b"]) } + if msgs[""] != 2 { + t.Errorf("Expected 2 message for /, got %v", msgs[""]) + } } func TestPathMatch(t *testing.T) { @@ -45,7 +55,8 @@ func TestPathMatch(t *testing.T) { pattern, path string exp bool }{ - {"", "", false}, + {"", "", true}, + {"/", "/", true}, {"/a/b/c", "/a/b/c", true}, {"/a/b/c", "/a/b/c/d", false}, {"/a/b/c/", "/a/b/c/d", true},