Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Root path support for ServeMux #45

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions message.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:]
}
Expand Down
6 changes: 3 additions & 3 deletions servmux.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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")
}
Expand Down
13 changes: 12 additions & 1 deletion servmux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -31,21 +35,28 @@ 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"])
}
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) {
tests := []struct {
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},
Expand Down