forked from mtusi2026/mtusi2026lab2
chore: port lab 1 solution
This commit is contained in:
@@ -0,0 +1,30 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type requestIDContextKey struct{}
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := r.Header.Get("X-Request-Id")
|
||||
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), requestIDContextKey{}, requestID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDContextKey{}).(string)
|
||||
return id
|
||||
}
|
||||
Reference in New Issue
Block a user