Skip to content

Commit

Permalink
Adds RequestIDHandler function to RequestID middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
zacscoding committed Jun 22, 2021
1 parent 1ac4a8f commit 78a0ea2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
6 changes: 6 additions & 0 deletions middleware/request_id.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ type (
// Generator defines a function to generate an ID.
// Optional. Default value random.String(32).
Generator func() string

// RequestIDHandler defines a function which is executed for a request id.
RequestIDHandler func(echo.Context, string)
}
)

Expand Down Expand Up @@ -53,6 +56,9 @@ func RequestIDWithConfig(config RequestIDConfig) echo.MiddlewareFunc {
rid = config.Generator()
}
res.Header().Set(echo.HeaderXRequestID, rid)
if config.RequestIDHandler != nil {
config.RequestIDHandler(c, rid)
}

return next(c)
}
Expand Down
11 changes: 9 additions & 2 deletions middleware/request_id_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,20 @@ func TestRequestID(t *testing.T) {
h(c)
assert.Len(t, rec.Header().Get(echo.HeaderXRequestID), 32)

// Custom generator
// Custom generator and handler
customID := "customGenerator"
calledHandler := false
rid = RequestIDWithConfig(RequestIDConfig{
Generator: func() string { return "customGenerator" },
Generator: func() string { return customID },
RequestIDHandler: func(_ echo.Context, id string) {
calledHandler = true
assert.Equal(t, customID, id)
},
})
h = rid(handler)
h(c)
assert.Equal(t, rec.Header().Get(echo.HeaderXRequestID), "customGenerator")
assert.True(t, calledHandler)
}

func TestRequestID_IDNotAltered(t *testing.T) {
Expand Down

0 comments on commit 78a0ea2

Please sign in to comment.