summaryrefslogblamecommitdiff
path: root/request_id.go
blob: 67a0c8240d77647186263edfb93410d5b3d037ef (plain) (tree)






































                                                                                                            
package middleware

import (
	"context"
	"net/http"

	"github.com/google/uuid"
)

type ctxKeyRequestID int

const (
	RequestIDKey    ctxKeyRequestID = 0
	RequestIDHeader string          = "X-Request-ID"
)

func RequestID(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestID := r.Header.Get(RequestIDHeader)
		if requestID == "" {
			requestID = uuid.NewString()
		}

		handler.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), RequestIDKey, requestID)))
	})
}

func GetRequestID(r *http.Request) string {
	rid := r.Context().Value(RequestIDKey)
	if rid == nil {
		return ""
	}
	srid, ok := rid.(string)
	if !ok {
		return ""
	}

	return srid
}