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