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 2 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
35 changes: 35 additions & 0 deletions _examples/api-middleware/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package main
joeriddles marked this conversation as resolved.
Show resolved Hide resolved

import (
"fmt"
"net/http"

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

func main() {
r := chi.NewRouter()
r.Use(ApiMiddleware(r))

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)
}

// Middleware that prints the API pattern before the request is handled
func ApiMiddleware(router chi.Router) func(http.Handler) http.Handler {
joeriddles marked this conversation as resolved.
Show resolved Hide resolved
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
rctx := chi.NewRouteContext()
path := r.URL.Path
op := r.Method
api := router.Find(rctx, op, path)
joeriddles marked this conversation as resolved.
Show resolved Hide resolved

fmt.Printf("api=%s\n", api)

next.ServeHTTP(w, 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
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