chi icon indicating copy to clipboard operation
chi copied to clipboard

Superfluous wildcard "*" keys in `URLParams` struct

Open donwitobanana opened this issue 2 years ago • 2 comments

Hi!

I want to get all path params for a given request having a router that is mounted onto another one:

func main() {
	r := chi.NewRouter()
	r.Get("/{id}", myHandler)

	baseRouter := chi.NewRouter()
	baseRouter.Mount("/base", r)

	go http.ListenAndServe(":8080", baseRouter)

	http.DefaultClient.Get("http://localhost:8080/base/123")
}


func myHandler(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	urlParams := chi.RouteContext(ctx).URLParams

	for i, key := range urlParams.Keys {
		fmt.Printf("key: \"%s\", value: \"%s\"\n", key, urlParams.Values[i])
	}
}

The output is:

key: "*", value: ""
key: "id", value: "123"

I'm expecting to get id parameter only, but what I get additionally is this empty wildcard "*" parameter. This doesn't happen when using router without mounting.

Is there a way to get only defined path parameters other than manually filtering out wildcard ones? I'm not sure if this is a bug or not, but shouldn't this be handled in the internal urlParams struct field and not in the exported one at least?

donwitobanana avatar Jun 15 '23 14:06 donwitobanana

I think it might be confusing because you're getting keys of the sub-router. Can you describe the endpoints you have and what you're looking to capture?

pkieltyka avatar Jun 28 '23 17:06 pkieltyka

My use case is to capture all URL params and log them in the middleware. I have multiple sub-routers so I end up having multiple "*" parameters in URLParams struct. If this is something that chi needs internally, then I would expect there's another private field in RouteContext to store that, but exported URLParams contains actual URL parameters only, so I don't have to filter them out when reading URLParams field.

donwitobanana avatar Jun 29 '23 14:06 donwitobanana