Skip to content

Commit

Permalink
Merge pull request #207 from redben/gin-id-from-route
Browse files Browse the repository at this point in the history
feat(gin): user gin.Context.FullPath() as URLPath
  • Loading branch information
slok committed Apr 19, 2024
2 parents c472df0 + 115aa24 commit 2d68954
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
2 changes: 1 addition & 1 deletion middleware/gin/gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (r *reporter) Method() string { return r.c.Request.Method }

func (r *reporter) Context() context.Context { return r.c.Request.Context() }

func (r *reporter) URLPath() string { return r.c.Request.URL.Path }
func (r *reporter) URLPath() string { return r.c.FullPath() }

func (r *reporter) StatusCode() int { return r.c.Writer.Status() }

Expand Down
39 changes: 38 additions & 1 deletion middleware/gin/gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ func TestMiddleware(t *testing.T) {
tests := map[string]struct {
handlerID string
config middleware.Config
route string
req func() *http.Request
mock func(m *mmetrics.Recorder)
handler func() gin.HandlerFunc
Expand Down Expand Up @@ -86,6 +87,37 @@ func TestMiddleware(t *testing.T) {
expRespCode: 202,
expRespBody: `{"test":"one"}`,
},

"A default HTTP middleware should set template route as route label": {
route: "/test/:id",
req: func() *http.Request {
return httptest.NewRequest(http.MethodPost, "/test/12", nil)
},
mock: func(m *mmetrics.Recorder) {
expHTTPReqProps := metrics.HTTPReqProperties{
ID: "/test/:id",
Service: "",
Method: "POST",
Code: "202",
}
m.On("ObserveHTTPRequestDuration", mock.Anything, expHTTPReqProps, mock.Anything).Once()
m.On("ObserveHTTPResponseSize", mock.Anything, expHTTPReqProps, int64(14)).Once()

expHTTPProps := metrics.HTTPProperties{
ID: "/test/:id",
Service: "",
}
m.On("AddInflightRequests", mock.Anything, expHTTPProps, 1).Once()
m.On("AddInflightRequests", mock.Anything, expHTTPProps, -1).Once()
},
handler: func() gin.HandlerFunc {
return func(c *gin.Context) {
c.JSON(202, map[string]string{"test": "one"})
}
},
expRespCode: 202,
expRespBody: `{"test":"one"}`,
},
}

for name, test := range tests {
Expand All @@ -101,7 +133,12 @@ func TestMiddleware(t *testing.T) {
mdlw := middleware.New(middleware.Config{Recorder: mr})
engine := gin.New()
req := test.req()
engine.Handle(req.Method, req.URL.Path,

relativePath := req.URL.Path
if test.route != "" {
relativePath = test.route
}
engine.Handle(req.Method, relativePath,
ginmiddleware.Handler(test.handlerID, mdlw),
test.handler())

Expand Down

0 comments on commit 2d68954

Please sign in to comment.