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

Fix inconsistent path parameter handling in Router #6

Merged
merged 1 commit into from
Jul 30, 2024
Merged
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
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
Loading