Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ How to release a new version:
- Manually release new version.

## [Unreleased]
### Changed
- In `http.RequestIDMiddleware`, the `request_id` is now always set in the response header.


## [0.8.0] - 2024-11-14
### Added
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ module go.strv.io/net

go 1.23.0

toolchain go1.25.4
toolchain go1.25.6

require (
github.com/99designs/gqlgen v0.17.78
Expand Down
5 changes: 4 additions & 1 deletion http/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ const (
// RequestIDFunc is used for obtaining a request ID from the HTTP header.
type RequestIDFunc func(h http.Header) string

// RequestIDMiddleware saves request ID into the request context.
// RequestIDMiddleware saves request ID into the request context and response header.
Comment thread
milaguyenlam marked this conversation as resolved.
Resolved
// If context already contains request ID, next handler is called.
// If the user provided function returns empty request ID, a new one is generated.
func RequestIDMiddleware(f RequestIDFunc) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if requestID := net.RequestIDFromCtx(r.Context()); requestID != "" {
w.Header().Set(Header.XRequestID, requestID)
next.ServeHTTP(w, r)
return
}
Expand All @@ -34,6 +35,8 @@ func RequestIDMiddleware(f RequestIDFunc) func(http.Handler) http.Handler {
requestID = net.NewRequestID()
}

w.Header().Set(Header.XRequestID, requestID)

ctx := net.WithRequestID(r.Context(), requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
Expand Down