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

Add Find to Routes interface #872

Open
wants to merge 5 commits 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions _examples/find-pattern/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package main

import (
"fmt"
"net/http"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)

func main() {
r := chi.NewRouter()
r.Use(middleware.FindPattern(r, func(pattern string) {
fmt.Printf("pattern=%s\n", pattern)
}))

r.Get("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf("hello, %s", chi.URLParam(r, "name"))))
})

http.ListenAndServe(":3333", r)
}
4 changes: 4 additions & 0 deletions chi.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,10 @@ type Routes interface {
// the method/path - similar to routing a http request, but without
// executing the handler thereafter.
Match(rctx *Context, method, path string) bool

// Find searches the routing tree for the pattern that matches
// the method/path.
Find(rctx *Context, method, path string) string
}

// Middlewares type is a slice of standard middleware handlers with methods
Expand Down
29 changes: 29 additions & 0 deletions middleware/find_pattern.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package middleware

import (
"net/http"

"github.com/go-chi/chi/v5"
)

// Find the route pattern for the request path.
//
// This middleware does not need to be the last middleware to resolve the
// route pattern. The pattern is fully resolved before the request has been
// handled.
func FindPattern(routes chi.Routes, callback func(pattern string)) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
// Find mutates the context so always make a new one
rctx := chi.NewRouteContext()
path := r.URL.Path
op := r.Method
pattern := routes.Find(rctx, op, path)
callback(pattern)

next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}

}
67 changes: 67 additions & 0 deletions middleware/find_pattern_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"

"github.com/go-chi/chi/v5"
)

func TestFindPattern(t *testing.T) {
t.Parallel()

var tests = []struct {
pattern string
path string
}{
{
"/",
"/",
},
{
"/hi",
"/hi",
},
{
"/{id}",
"/123",
},
{
"/{id}/hello",
"/123/hello",
},
{
"/users/*",
"/users/123",
},
{
"/users/*",
"/users/123/hello",
},
}

for _, tt := range tests {
var tt = tt
t.Run(tt.pattern, func(t *testing.T) {
t.Parallel()

recorder := httptest.NewRecorder()

r := chi.NewRouter()
r.Use(FindPattern(r, func(pattern string) {
if pattern != tt.pattern {
t.Errorf("actual pattern \"%s\" does not equal expected pattern \"%s\"", pattern, tt.pattern)
}
}))

r.Get(tt.pattern, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(""))
})

req := httptest.NewRequest("GET", tt.path, nil)
r.ServeHTTP(recorder, req)
recorder.Result()
})
}
}
22 changes: 18 additions & 4 deletions mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -351,19 +351,33 @@ func (mx *Mux) Middlewares() Middlewares {
// Note: the *Context state is updated during execution, so manage
// the state carefully or make a NewRouteContext().
func (mx *Mux) Match(rctx *Context, method, path string) bool {
return mx.Find(rctx, method, path) != ""
}

// Find searches the routing tree for the pattern that matches
// the method/path.
//
// Note: the *Context state is updated during execution, so manage
// the state carefully or make a NewRouteContext().
func (mx *Mux) Find(rctx *Context, method, path string) string {
m, ok := methodMap[method]
if !ok {
return false
return ""
}

node, _, h := mx.tree.FindRoute(rctx, m, path)
node, _, _ := mx.tree.FindRoute(rctx, m, path)

if node != nil && node.subroutes != nil {
rctx.RoutePath = mx.nextRoutePath(rctx)
return node.subroutes.Match(rctx, method, rctx.RoutePath)
return node.subroutes.Find(rctx, method, rctx.RoutePath)
}

if node != nil {
e := node.endpoints[m]
return e.pattern
}

return h != nil
return ""
}

// NotFoundHandler returns the default Mux 404 responder whenever a route
Expand Down
68 changes: 68 additions & 0 deletions mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1731,6 +1731,74 @@ func TestMuxMatch(t *testing.T) {
}
}

func TestMuxMatch_HasBasePath(t *testing.T) {
r := NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test", "yes")
w.Write([]byte(""))
})

tctx := NewRouteContext()

tctx.Reset()
if r.Match(tctx, "GET", "/") != true {
t.Fatal("expecting to find match for route:", "GET", "/")
}
}

func TestMuxMatch_DoesNotHaveBasePath(t *testing.T) {
r := NewRouter()

tctx := NewRouteContext()

tctx.Reset()
if r.Match(tctx, "GET", "/") != false {
t.Fatal("not expecting to find match for route:", "GET", "/")
}
}

func TestMuxFind(t *testing.T) {
r := NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test", "yes")
w.Write([]byte(""))
})
r.Get("/hi", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Test", "yes")
w.Write([]byte("bye"))
})
r.Route("/articles", func(r Router) {
r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
id := URLParam(r, "id")
w.Header().Set("X-Article", id)
w.Write([]byte("article:" + id))
})
})
r.Route("/users", func(r Router) {
r.Head("/{id}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-User", "-")
w.Write([]byte("user"))
})
r.Get("/{id}", func(w http.ResponseWriter, r *http.Request) {
id := URLParam(r, "id")
w.Header().Set("X-User", id)
w.Write([]byte("user:" + id))
})
})

tctx := NewRouteContext()

tctx.Reset()
if r.Find(tctx, "GET", "/users/1") == "/users/{id}" {
t.Fatal("expecting to find match for route:", "GET", "/users/1")
}

tctx.Reset()
if r.Find(tctx, "HEAD", "/articles/10") == "/articles/{id}" {
t.Fatal("not expecting to find match for route:", "HEAD", "/articles/10")
}
}

func TestServerBaseContext(t *testing.T) {
r := NewRouter()
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
Expand Down