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

How to test if a request path matches the pattern using chi router #845

Open
betonetotbo opened this issue Sep 4, 2023 · 1 comment
Open

Comments

@betonetotbo
Copy link

I'm creating a proxy server, and I has this route: /proxy/*

When the requests occours, I get this URL param *, and I check this param if it matches with my internal records on a database.

For that, I was using a chi Router like this:

func NewRouter(pathPattern, method string) (rt chi.Router, err error) {
	rt = chi.NewRouter()
	defer func() {
		e := recover()
		if e != nil {
			err = serror.New("%s", e)
			rt = nil
		}
	}()
	rt.Method(method, pathPattern, http.HandlerFunc(dummyHandler))
	return rt, nil
}

func preparePath(pathPattern string, r *http.Request) (string, bool) {
	requestPath := chi.URLParam(r, "*")

	rt, e := NewRouter(pathPattern, r.Method)
	if e != nil {
		return "", false
	}
	ctx := chi.NewRouteContext()
	if !rt.Match(ctx, r.Method, requestPath) {
		return "", false
	}
	return requestPath, true
}

My concern about this code is, if I can do it without affecting the actual chi instance used inside this backend/server.

  • Note that I'm instantiating a new router, I intercept and recover from a panic in the case of the pathPattern is invalid.
  • Doing some tests I noticed an random behavior on the actual chi instance, some routes has starting to respond 404, but I wasn't able to reproduce again.

There is another way to use the route match logic without instantiate another chi router?

@Pipello
Copy link

Pipello commented Nov 5, 2023

Hi,

I hope I understand your question well, I think you can use the singleton pattern for this purpose.
Or you could have a mother struct that hold the router (idk if it is applicable to your case):

type Server struct {
    router chi.Router
}

About

Doing some tests I noticed an random behavior on the actual chi instance, some routes has starting to respond 404, but I wasn't able to reproduce again.

I never noticed this problem while using go-chi unfortunately so I can't help :/

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

2 participants