30 lines
652 B
Go
30 lines
652 B
Go
package middleware
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/charawein/mtusi2026lab6/internal/transport/httputil"
|
|
)
|
|
|
|
func RequestID(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 = newRequestID()
|
|
}
|
|
w.Header().Set("X-Request-Id", id)
|
|
ctx := httputil.ContextWithRequestID(r.Context(), id)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
func newRequestID() string {
|
|
var b [12]byte
|
|
if _, err := rand.Read(b[:]); err != nil {
|
|
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
|
}
|
|
return fmt.Sprintf("%x", b[:])
|
|
}
|