Skip to content

Commit 7a12559

Browse files
committed
add tests && examples
1 parent dc47ac7 commit 7a12559

File tree

3 files changed

+59
-2
lines changed

3 files changed

+59
-2
lines changed

example_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package mux_test
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
7+
"github.com/go-http-utils/mux"
8+
)
9+
10+
func Example() {
11+
m := mux.New()
12+
13+
m.Get("/:type(a|b)/:id", mux.HandlerFunc(func(res http.ResponseWriter, req *http.Request, params map[string]string) {
14+
res.WriteHeader(http.StatusOK)
15+
16+
fmt.Println(params["type"])
17+
fmt.Println(params[":id"])
18+
19+
res.Write([]byte("Hello Worlkd"))
20+
}))
21+
22+
http.ListenAndServe(":8080", m)
23+
}

mux.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ func (m Mux) ServeHTTP(res http.ResponseWriter, req *http.Request) {
8383

8484
if method == http.MethodOptions {
8585
allows := []string{}
86-
res.WriteHeader(http.StatusNoContent)
8786

8887
for m, n := range m.root {
8988
if _, _, ok := n.Match(uri); ok {
@@ -92,7 +91,7 @@ func (m Mux) ServeHTTP(res http.ResponseWriter, req *http.Request) {
9291
}
9392

9493
res.Header().Add(headers.Allow, strings.Join(allows, ", "))
95-
94+
res.WriteHeader(http.StatusNoContent)
9695
return
9796
}
9897

mux_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"strings"
88
"testing"
99

10+
"github.com/go-http-utils/headers"
1011
"github.com/stretchr/testify/suite"
1112
)
1213

@@ -84,6 +85,40 @@ func (s *MuxSuite) TestMethods() {
8485
}
8586
}
8687

88+
func (s *MuxSuite) TestNotAllowed() {
89+
req, err := http.NewRequest("TEST", s.server.URL+"/123", nil)
90+
91+
s.Nil(err)
92+
93+
res, err := sendRequest(req)
94+
95+
s.Nil(err)
96+
s.Equal(http.StatusMethodNotAllowed, res.StatusCode)
97+
}
98+
99+
func (s *MuxSuite) TestNotFound() {
100+
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/123/test", nil)
101+
102+
s.Nil(err)
103+
104+
res, err := sendRequest(req)
105+
106+
s.Nil(err)
107+
s.Equal(http.StatusNotFound, res.StatusCode)
108+
}
109+
110+
func (s *MuxSuite) TestOptions() {
111+
req, err := http.NewRequest(http.MethodOptions, s.server.URL+"/get/123", nil)
112+
113+
s.Nil(err)
114+
115+
res, err := sendRequest(req)
116+
117+
s.Nil(err)
118+
s.Equal(http.StatusNoContent, res.StatusCode)
119+
s.Equal("GET", res.Header.Get(headers.Allow))
120+
}
121+
87122
func TestMux(t *testing.T) {
88123
suite.Run(t, new(MuxSuite))
89124
}

0 commit comments

Comments
 (0)