go-chi/chi

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

betonetotbo opened this issue · 1 comments

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?

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 :/