summaryrefslogblamecommitdiff
path: root/middleware/request_id.go
blob: feb5afab8aa2ad3169c61f01d4c6757f21c00f92 (plain) (tree)
1
2
3
4
5
6
7





                  
                                 












                                                                              
                                                                                                             



                                           
                                                  









                                
package middleware

import (
	"context"
	"net/http"

	"go.neonxp.ru/mux/ctxlib"
	"go.neonxp.ru/objectid"
)

const RequestIDHeader string = "X-Request-ID"

func RequestID(next http.Handler) http.Handler {
	objectid.Seed()
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		requestID := r.Header.Get(RequestIDHeader)
		if requestID == "" {
			requestID = objectid.New().String()
		}

		next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxlib.RequestID, requestID)))
	})
}

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

	return srid
}