24 lines
591 B
Go
24 lines
591 B
Go
package middleware
|
||
|
||
import (
|
||
"net/http"
|
||
|
||
"git.toowon.com/jimmy/go-common/logger"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// RequestID 为每个请求生成或透传 Request ID,写入 context 与响应头
|
||
func RequestID() func(http.Handler) http.Handler {
|
||
return func(next http.Handler) http.Handler {
|
||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
id := r.Header.Get("X-Request-ID")
|
||
if id == "" {
|
||
id = uuid.NewString()
|
||
}
|
||
w.Header().Set("X-Request-ID", id)
|
||
ctx := logger.WithRequestID(r.Context(), id)
|
||
next.ServeHTTP(w, r.WithContext(ctx))
|
||
})
|
||
}
|
||
}
|