summaryrefslogtreecommitdiff
path: root/request_id.go
blob: 016b44abcda7a546fe2282e5f4eed97a484b5352 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package middleware

import (
	"context"
	"net/http"

	"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(), 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
}