From f7c973346bdf44aac122a68d5f163490389be2d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Eduardo=20Bou=C3=A7as?= Date: Sun, 31 Oct 2021 15:19:53 +0000 Subject: [PATCH] Add URLParam function --- router/router.go | 8 ++++++++ router/router_test.go | 15 +++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/router/router.go b/router/router.go index 1b7f91c..2d03663 100644 --- a/router/router.go +++ b/router/router.go @@ -52,6 +52,9 @@ type Router interface { Mount(pattern string, h http.Handler) ServeHTTP(http.ResponseWriter, *http.Request) + + // Returns the value of a URL parameter + URLParam(*http.Request, string) string } // New creates a router with sensible defaults (xff, request id, cors) @@ -151,6 +154,11 @@ func (r *chiWrapper) Mount(pattern string, h http.Handler) { r.chi.Mount(pattern, h) } +// Returns the value of a URL parameter +func (r *chiWrapper) URLParam(req *http.Request, name string) string { + return chi.URLParam(req, name) +} + // ======================================= // HTTP handler with custom error payload // ======================================= diff --git a/router/router_test.go b/router/router_test.go index 8dc0132..65feeee 100644 --- a/router/router_test.go +++ b/router/router_test.go @@ -147,6 +147,21 @@ func TestVersionHeader(t *testing.T) { } } +func TestURLParam(t *testing.T) { + r := New(logrus.WithField("test", t.Name()), OptEnableTracing("some-service")) + + r.Get("/objects/{objectId}", func(w http.ResponseWriter, req *http.Request) error { + w.Write([]byte(r.URLParam(req, "objectId"))) + w.WriteHeader(http.StatusOK) + return nil + }) + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, httptest.NewRequest("GET", "/objects/some-object", nil)) + assert.Equal(t, []byte("some-object"), rec.Body.Bytes()) + assert.Equal(t, http.StatusOK, rec.Code) +} + func do(t *testing.T, opts []Option, svcName, path string, handler APIHandler, req *http.Request) *httptest.ResponseRecorder { if opts == nil { opts = []Option{}