context.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package logging
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/rs/xid"
  6. )
  7. type key int
  8. const (
  9. // RequestIDKey is the context key that should store the request identifier.
  10. RequestIDKey key = iota
  11. // UserIDKey is the context key that should store the user identifier.
  12. UserIDKey
  13. )
  14. // NewRequestID creates a new request id using github.com/rs/xid.
  15. func NewRequestID() string {
  16. return xid.New().String()
  17. }
  18. // RequestID returns a new middleware that gets the given header and sets it
  19. // in the context so it can be written in the logger. If the header does not
  20. // exists or it's the empty string, it uses github.com/rs/xid to create a new
  21. // one.
  22. func RequestID(headerName string) func(next http.Handler) http.Handler {
  23. return func(next http.Handler) http.Handler {
  24. fn := func(w http.ResponseWriter, req *http.Request) {
  25. requestID := req.Header.Get(headerName)
  26. if requestID == "" {
  27. requestID = NewRequestID()
  28. req.Header.Set(headerName, requestID)
  29. }
  30. ctx := WithRequestID(req.Context(), requestID)
  31. next.ServeHTTP(w, req.WithContext(ctx))
  32. }
  33. return http.HandlerFunc(fn)
  34. }
  35. }
  36. // WithRequestID returns a new context with the given requestID added to the
  37. // context.
  38. func WithRequestID(ctx context.Context, requestID string) context.Context {
  39. return context.WithValue(ctx, RequestIDKey, requestID)
  40. }
  41. // GetRequestID returns the request id from the context if it exists.
  42. func GetRequestID(ctx context.Context) (string, bool) {
  43. v, ok := ctx.Value(RequestIDKey).(string)
  44. return v, ok
  45. }
  46. // WithUserID decodes the token, extracts the user from the payload and stores
  47. // it in the context.
  48. func WithUserID(ctx context.Context, userID string) context.Context {
  49. return context.WithValue(ctx, UserIDKey, userID)
  50. }
  51. // GetUserID returns the request id from the context if it exists.
  52. func GetUserID(ctx context.Context) (string, bool) {
  53. v, ok := ctx.Value(UserIDKey).(string)
  54. return v, ok
  55. }