lab1
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Request-ID"
|
||||
|
||||
type requestIDKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
id, _ := ctx.Value(requestIDKey{}).(string)
|
||||
|
||||
return id
|
||||
}
|
||||
|
||||
func withRequestID(ctx context.Context, id string) context.Context {
|
||||
return context.WithValue(ctx, requestIDKey{}, id)
|
||||
}
|
||||
|
||||
func requestIDMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get(requestIDHeader)
|
||||
if id == "" {
|
||||
id = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set(requestIDHeader, id)
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(withRequestID(r.Context(), id)))
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user