request_id.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package middleware
  2. // Ported from Goji's middleware, source:
  3. // https://github.com/zenazn/goji/tree/master/web/middleware
  4. import (
  5. "context"
  6. "crypto/rand"
  7. "encoding/base64"
  8. "fmt"
  9. "net/http"
  10. "os"
  11. "strings"
  12. "sync/atomic"
  13. )
  14. // Key to use when setting the request ID.
  15. type ctxKeyRequestID int
  16. // RequestIDKey is the key that holds the unique request ID in a request context.
  17. const RequestIDKey ctxKeyRequestID = 0
  18. // RequestIDHeader is the name of the HTTP Header which contains the request id.
  19. // Exported so that it can be changed by developers
  20. var RequestIDHeader = "X-Request-Id"
  21. var prefix string
  22. var reqid atomic.Uint64
  23. // A quick note on the statistics here: we're trying to calculate the chance that
  24. // two randomly generated base62 prefixes will collide. We use the formula from
  25. // http://en.wikipedia.org/wiki/Birthday_problem
  26. //
  27. // P[m, n] \approx 1 - e^{-m^2/2n}
  28. //
  29. // We ballpark an upper bound for $m$ by imagining (for whatever reason) a server
  30. // that restarts every second over 10 years, for $m = 86400 * 365 * 10 = 315360000$
  31. //
  32. // For a $k$ character base-62 identifier, we have $n(k) = 62^k$
  33. //
  34. // Plugging this in, we find $P[m, n(10)] \approx 5.75%$, which is good enough for
  35. // our purposes, and is surely more than anyone would ever need in practice -- a
  36. // process that is rebooted a handful of times a day for a hundred years has less
  37. // than a millionth of a percent chance of generating two colliding IDs.
  38. func init() {
  39. hostname, err := os.Hostname()
  40. if hostname == "" || err != nil {
  41. hostname = "localhost"
  42. }
  43. var buf [12]byte
  44. var b64 string
  45. for len(b64) < 10 {
  46. rand.Read(buf[:])
  47. b64 = base64.StdEncoding.EncodeToString(buf[:])
  48. b64 = strings.NewReplacer("+", "", "/", "").Replace(b64)
  49. }
  50. prefix = fmt.Sprintf("%s/%s", hostname, b64[0:10])
  51. }
  52. // RequestID is a middleware that injects a request ID into the context of each
  53. // request. A request ID is a string of the form "host.example.com/random-0001",
  54. // where "random" is a base62 random string that uniquely identifies this go
  55. // process, and where the last number is an atomically incremented request
  56. // counter.
  57. func RequestID(next http.Handler) http.Handler {
  58. fn := func(w http.ResponseWriter, r *http.Request) {
  59. ctx := r.Context()
  60. requestID := r.Header.Get(RequestIDHeader)
  61. if requestID == "" {
  62. myid := reqid.Add(1)
  63. requestID = fmt.Sprintf("%s-%06d", prefix, myid)
  64. }
  65. ctx = context.WithValue(ctx, RequestIDKey, requestID)
  66. next.ServeHTTP(w, r.WithContext(ctx))
  67. }
  68. return http.HandlerFunc(fn)
  69. }
  70. // GetReqID returns a request ID from the given context if one is present.
  71. // Returns the empty string if a request ID cannot be found.
  72. func GetReqID(ctx context.Context) string {
  73. if ctx == nil {
  74. return ""
  75. }
  76. if reqID, ok := ctx.Value(RequestIDKey).(string); ok {
  77. return reqID
  78. }
  79. return ""
  80. }
  81. // NextRequestID generates the next request ID in the sequence.
  82. func NextRequestID() uint64 {
  83. return reqid.Add(1)
  84. }