Skip to content

Commit 2d68954

Browse files
authored
Merge pull request #207 from redben/gin-id-from-route
feat(gin): user gin.Context.FullPath() as URLPath
2 parents c472df0 + 115aa24 commit 2d68954

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

middleware/gin/gin.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ func (r *reporter) Method() string { return r.c.Request.Method }
2727

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

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

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

middleware/gin/gin_test.go

+38-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ func TestMiddleware(t *testing.T) {
2121
tests := map[string]struct {
2222
handlerID string
2323
config middleware.Config
24+
route string
2425
req func() *http.Request
2526
mock func(m *mmetrics.Recorder)
2627
handler func() gin.HandlerFunc
@@ -86,6 +87,37 @@ func TestMiddleware(t *testing.T) {
8687
expRespCode: 202,
8788
expRespBody: `{"test":"one"}`,
8889
},
90+
91+
"A default HTTP middleware should set template route as route label": {
92+
route: "/test/:id",
93+
req: func() *http.Request {
94+
return httptest.NewRequest(http.MethodPost, "/test/12", nil)
95+
},
96+
mock: func(m *mmetrics.Recorder) {
97+
expHTTPReqProps := metrics.HTTPReqProperties{
98+
ID: "/test/:id",
99+
Service: "",
100+
Method: "POST",
101+
Code: "202",
102+
}
103+
m.On("ObserveHTTPRequestDuration", mock.Anything, expHTTPReqProps, mock.Anything).Once()
104+
m.On("ObserveHTTPResponseSize", mock.Anything, expHTTPReqProps, int64(14)).Once()
105+
106+
expHTTPProps := metrics.HTTPProperties{
107+
ID: "/test/:id",
108+
Service: "",
109+
}
110+
m.On("AddInflightRequests", mock.Anything, expHTTPProps, 1).Once()
111+
m.On("AddInflightRequests", mock.Anything, expHTTPProps, -1).Once()
112+
},
113+
handler: func() gin.HandlerFunc {
114+
return func(c *gin.Context) {
115+
c.JSON(202, map[string]string{"test": "one"})
116+
}
117+
},
118+
expRespCode: 202,
119+
expRespBody: `{"test":"one"}`,
120+
},
89121
}
90122

91123
for name, test := range tests {
@@ -101,7 +133,12 @@ func TestMiddleware(t *testing.T) {
101133
mdlw := middleware.New(middleware.Config{Recorder: mr})
102134
engine := gin.New()
103135
req := test.req()
104-
engine.Handle(req.Method, req.URL.Path,
136+
137+
relativePath := req.URL.Path
138+
if test.route != "" {
139+
relativePath = test.route
140+
}
141+
engine.Handle(req.Method, relativePath,
105142
ginmiddleware.Handler(test.handlerID, mdlw),
106143
test.handler())
107144

0 commit comments

Comments
 (0)