diff options
author | Rainer Borene <rainerborene@users.noreply.github.com> | 2021-12-15 04:17:53 -0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-12-15 00:17:53 -0700 |
commit | 180ae0cc4843ecc3c7ddcb6e978ebfd474ed07f9 (patch) | |
tree | 360fc88ecf0cdce992567ac049e5ea50277d31e5 /modules/caddyhttp/replacer.go | |
parent | a1c41210d34c629c3b5cdbdca74c540fde752aad (diff) |
caddyhttp: Implement http.request.uuid placeholder (#4285)
Diffstat (limited to 'modules/caddyhttp/replacer.go')
-rw-r--r-- | modules/caddyhttp/replacer.go | 19 |
1 files changed, 19 insertions, 0 deletions
diff --git a/modules/caddyhttp/replacer.go b/modules/caddyhttp/replacer.go index 2cf456f..26f7e0b 100644 --- a/modules/caddyhttp/replacer.go +++ b/modules/caddyhttp/replacer.go @@ -40,6 +40,7 @@ import ( "github.com/caddyserver/caddy/v2" "github.com/caddyserver/caddy/v2/modules/caddytls" + "github.com/google/uuid" ) // NewTestReplacer creates a replacer for an http.Request @@ -54,6 +55,7 @@ func NewTestReplacer(req *http.Request) *caddy.Replacer { func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.ResponseWriter) { SetVar(req.Context(), "start_time", time.Now()) + SetVar(req.Context(), "uuid", new(requestID)) httpVars := func(key string) (interface{}, bool) { if req != nil { @@ -146,6 +148,9 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo case "http.request.duration": start := GetVar(req.Context(), "start_time").(time.Time) return time.Since(start), true + case "http.request.uuid": + id := GetVar(req.Context(), "uuid").(*requestID) + return id.String(), true case "http.request.body": if req.Body == nil { return "", true @@ -400,6 +405,20 @@ func getTLSPeerCert(cs *tls.ConnectionState) *x509.Certificate { return cs.PeerCertificates[0] } +type requestID struct { + value string +} + +// Lazy generates UUID string or return cached value if present +func (rid *requestID) String() string { + if rid.value == "" { + if id, err := uuid.NewRandom(); err == nil { + rid.value = id.String() + } + } + return rid.value +} + const ( reqCookieReplPrefix = "http.request.cookie." reqHeaderReplPrefix = "http.request.header." |