Skip to content

Commit

Permalink
add tests && examples
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidCai1111 committed Dec 3, 2016
1 parent dc47ac7 commit 7a12559
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 2 deletions.
23 changes: 23 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package mux_test

import (
"fmt"
"net/http"

"github.com/go-http-utils/mux"
)

func Example() {
m := mux.New()

m.Get("/:type(a|b)/:id", mux.HandlerFunc(func(res http.ResponseWriter, req *http.Request, params map[string]string) {
res.WriteHeader(http.StatusOK)

fmt.Println(params["type"])
fmt.Println(params[":id"])

res.Write([]byte("Hello Worlkd"))
}))

http.ListenAndServe(":8080", m)
}
3 changes: 1 addition & 2 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ func (m Mux) ServeHTTP(res http.ResponseWriter, req *http.Request) {

if method == http.MethodOptions {
allows := []string{}
res.WriteHeader(http.StatusNoContent)

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

res.Header().Add(headers.Allow, strings.Join(allows, ", "))

res.WriteHeader(http.StatusNoContent)
return
}

Expand Down
35 changes: 35 additions & 0 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"
"testing"

"github.com/go-http-utils/headers"
"github.com/stretchr/testify/suite"
)

Expand Down Expand Up @@ -84,6 +85,40 @@ func (s *MuxSuite) TestMethods() {
}
}

func (s *MuxSuite) TestNotAllowed() {
req, err := http.NewRequest("TEST", s.server.URL+"/123", nil)

s.Nil(err)

res, err := sendRequest(req)

s.Nil(err)
s.Equal(http.StatusMethodNotAllowed, res.StatusCode)
}

func (s *MuxSuite) TestNotFound() {
req, err := http.NewRequest(http.MethodGet, s.server.URL+"/123/test", nil)

s.Nil(err)

res, err := sendRequest(req)

s.Nil(err)
s.Equal(http.StatusNotFound, res.StatusCode)
}

func (s *MuxSuite) TestOptions() {
req, err := http.NewRequest(http.MethodOptions, s.server.URL+"/get/123", nil)

s.Nil(err)

res, err := sendRequest(req)

s.Nil(err)
s.Equal(http.StatusNoContent, res.StatusCode)
s.Equal("GET", res.Header.Get(headers.Allow))
}

func TestMux(t *testing.T) {
suite.Run(t, new(MuxSuite))
}
Expand Down

0 comments on commit 7a12559

Please sign in to comment.