github.com/hellobchain/third_party@v0.0.0-20230331131523-deb0478a2e52/go-chi/chi/middleware/request_id.go (about)

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