Skip to content

Commit

Permalink
Merge pull request #6 from shellfu/issue_5
Browse files Browse the repository at this point in the history
Fix inconsistent path parameter handling in Router
  • Loading branch information
shellfu authored Jul 30, 2024
2 parents 86ae44d + a6ebbb0 commit 426617d
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 9 deletions.
10 changes: 3 additions & 7 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,9 @@ is matched. The handler function should take an http.ResponseWriter and an *http
as its parameters.
*/
func (r *Router) Handle(method string, path string, handler http.Handler) {
// Add route to router
route := &Route{
path: regexp.MustCompile("^" + path + "$"),
method: method,
handler: handler,
}
r.routes = append(r.routes, *route)
r.HandlerFunc(method, path, func(w http.ResponseWriter, req *http.Request) {
handler.ServeHTTP(w, req)
})
}

/*
Expand Down
35 changes: 33 additions & 2 deletions router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"reflect"
"regexp"
"strings"
"testing"

Expand Down Expand Up @@ -85,8 +86,9 @@ func TestRouter_Handle(t *testing.T) {
t.Errorf("unexpected method for route %d: expected=%s, actual=%s", i, tc.method, route.method)
}

if route.path.String() != "^"+tc.path+"$" {
t.Errorf("unexpected path for route %d: expected=%s, actual=%s", i, "^"+tc.path+"$", route.path.String())
expectedPathPattern := "^" + regexp.MustCompile(`:([\w-]+)`).ReplaceAllString(tc.path, `([-\w.]+)`) + "$"
if route.path.String() != expectedPathPattern {
t.Errorf("unexpected path for route %d: expected=%s, actual=%s", i, expectedPathPattern, route.path.String())
}

if route.handler == nil {
Expand All @@ -95,6 +97,35 @@ func TestRouter_Handle(t *testing.T) {
}
}

func TestRouter_Handle_ServeHTTP(t *testing.T) {
router := NewRouter()

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := router.Params(r)["id"]
w.WriteHeader(http.StatusOK)
_, err := w.Write([]byte("User ID: " + id))
if err != nil {
t.Fatalf("Error writing response: %v", err)
}
})

router.Handle("GET", "/users/:id", handler)

req := httptest.NewRequest("GET", "/users/123", nil)
w := httptest.NewRecorder()

router.ServeHTTP(w, req)

if w.Code != http.StatusOK {
t.Errorf("Expected status code 200, got %d", w.Code)
}

expectedBody := "User ID: 123"
if w.Body.String() != expectedBody {
t.Errorf("Expected response body %q, got %q", expectedBody, w.Body.String())
}
}

func TestParams(t *testing.T) {
testCases := []struct {
path string
Expand Down

0 comments on commit 426617d

Please sign in to comment.