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

Regex param doesn't match dots #758

Open
Nyoroon opened this issue Oct 31, 2022 · 5 comments
Open

Regex param doesn't match dots #758

Nyoroon opened this issue Oct 31, 2022 · 5 comments

Comments

@Nyoroon
Copy link

Nyoroon commented Oct 31, 2022

Example program:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

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

func main() {
	mux := chi.NewMux()
	mux.Get("/{param:.+}.json", func(w http.ResponseWriter, r *http.Request) {
		param := chi.URLParam(r, "param")
		_, _ = fmt.Fprintf(w, "param=%s", param)
	})

	rec := httptest.NewRecorder()
	req := httptest.NewRequest(http.MethodGet, "/param.json", nil)
	mux.ServeHTTP(rec, req)

	fmt.Printf("code: %d, body: %s\n", rec.Code, rec.Body)

	rec = httptest.NewRecorder()
	req = httptest.NewRequest(http.MethodGet, "/param.with.dots.json", nil)
	mux.ServeHTTP(rec, req)

	fmt.Printf("code: %d, body: %s\n", rec.Code, rec.Body)
}

Expected:

code: 200, body: param=param
code: 404, body: param=param.with.dots

Got:

code: 200, body: param=param
code: 404, body: 404 page not found
@samsapti
Copy link

@Nyoroon the . in regex means "any character", so if you want to match a literal ., you need to escape it. Your string would then be: "/{param:\\.+}.json".

@Nyoroon
Copy link
Author

Nyoroon commented Dec 21, 2022

@Nyoroon the . in regex means "any character", so if you want to match a literal ., you need to escape it. Your string would then be: "/{param:\\.+}.json".

Yeah, and I want to match "any character", but it matches "any character except dot". I have an example in post.

@samsapti
Copy link

Okay, have you tried "/{param:[.\\.]+}.json"?

@js-everts
Copy link

@Nyoroon

This is not really a problem with the regex, it fails due to ambiguity.

If you were to modify the param to "/{param:.+}:json" (note the colon, it can be anything else) then make the request /param.with.dots:json, this will work because there is no ambiguity, chi knows everything before the colon (:) is supposed to be the param.

I suggest you define a the route like this r.Get("/{param:.+\\.json}", ...), then strip out and process the param manually in your handler.

@6543
Copy link

6543 commented Apr 11, 2023

#811 only fix things partially ... see #813 but at lest it's a move in the right direction ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants