diff options
| author | Christine Dodrill <me@christine.website> | 2019-03-27 07:18:52 -0700 |
|---|---|---|
| committer | Christine Dodrill <me@christine.website> | 2019-03-27 07:18:52 -0700 |
| commit | d0ff1b2d04fc0caf57d99f1d34ce13cf4aae6a1a (patch) | |
| tree | 29ae006563834338e663452e6f810561596582ac /internal/middleware/requestid.go | |
| parent | 20c08e68d1218475d6c6f3ca8ae718e1f508c696 (diff) | |
| download | xesite-d0ff1b2d04fc0caf57d99f1d34ce13cf4aae6a1a.tar.xz xesite-d0ff1b2d04fc0caf57d99f1d34ce13cf4aae6a1a.zip | |
reorg: phase 1
Diffstat (limited to 'internal/middleware/requestid.go')
| -rw-r--r-- | internal/middleware/requestid.go | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/internal/middleware/requestid.go b/internal/middleware/requestid.go new file mode 100644 index 0000000..6914137 --- /dev/null +++ b/internal/middleware/requestid.go @@ -0,0 +1,31 @@ +package middleware + +import ( + "net/http" + + "github.com/celrenheit/sandflake" + "within.website/ln" +) + +// RequestID appends a unique (sandflake) request ID to each request's +// X-Request-Id header field, much like Heroku's router does. +func RequestID(next http.Handler) http.Handler { + var g sandflake.Generator + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := g.Next().String() + + if rid := r.Header.Get("X-Request-Id"); rid != "" { + id = rid + "," + id + } + + ctx := ln.WithF(r.Context(), ln.F{ + "request_id": id, + }) + r = r.WithContext(ctx) + + w.Header().Set("X-Request-Id", id) + r.Header.Set("X-Request-Id", id) + + next.ServeHTTP(w, r) + }) +} |
