I have two ways (middleware) of setting a specific header (if not set) to request but want to know if one is better/beneficial than the other and the reasons why.
Note: At some point I will need to log X-Request-Id
value in every single application log I have. If this plan affects your answer, I don't know. Just saying!
Context version
package middleware
import (
"context"
"github.com/google/uuid"
"net/http"
)
type CtxKey string
const CtxReqIdKey CtxKey = "X-Request-Id"
func RequestId(handler http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
CtxKey := req.Header.Get("X-Request-Id")
if CtxKey == "" {
CtxKey = uuid.New().String()
}
ctx1 := context.WithValue(req.Context(), CtxReqIdKey, CtxKey)
ctx2 := req.WithContext(ctx1)
handler.ServeHTTP(res, ctx2)
})
}
# Elsewhere: request.Context().Value(middleware.CtxReqIdKey)
Without context version
package middleware
import (
"github.com/google/uuid"
"net/http"
)
func RequestId(handler http.Handler) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.Header.Get("X-Request-Id") == "" {
req.Header.Set("X-Request-Id", uuid.New().String())
}
handler.ServeHTTP(res, req)
})
}
Usage
err := http.ListenAndServe(":8080", middleware.RequestId(Router))