Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 14, 00:15 UTC
caddyhttp: Implement http.request.uuid placeholder (#4285)
Rainer Borene committed
Dec 15, 2021 at 04:17 UTC
180ae0cc4843ecc3c7ddcb6e978ebfd474ed07f9
2 files changed
+20
modules/caddyhttp/app.go
+1
@@ -50,6 +50,7 @@ func init() {
50
// `{http.request.body}` | The request body (⚠️ inefficient; use only for debugging)
51
// `{http.request.cookie.*}` | HTTP request cookie
52
// `{http.request.duration}` | Time up to now spent handling the request (after decoding headers from client)
53
+// `{http.request.uuid}` | The request unique identifier
54
// `{http.request.header.*}` | Specific request header field
55
// `{http.request.host.labels.*}` | Request host labels (0-based from right); e.g. for foo.example.com: 0=com, 1=example, 2=foo
56
// `{http.request.host}` | The host part of the request's Host header
modules/caddyhttp/replacer.go
+19
@@ -40,6 +40,7 @@ import (
40
41
"github.com/caddyserver/caddy/v2"
42
"github.com/caddyserver/caddy/v2/modules/caddytls"
43
+ "github.com/google/uuid"
44
)
45
46
// NewTestReplacer creates a replacer for an http.Request
@@ -54,6 +55,7 @@ func NewTestReplacer(req *http.Request) *caddy.Replacer {
55
56
func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.ResponseWriter) {
57
SetVar(req.Context(), "start_time", time.Now())
58
+ SetVar(req.Context(), "uuid", new(requestID))
59
60
httpVars := func(key string) (interface{}, bool) {
61
if req != nil {
@@ -146,6 +148,9 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
148
case "http.request.duration":
149
start := GetVar(req.Context(), "start_time").(time.Time)
150
return time.Since(start), true
151
+ case "http.request.uuid":
152
+ id := GetVar(req.Context(), "uuid").(*requestID)
153
+ return id.String(), true
154
case "http.request.body":
155
if req.Body == nil {
156
return "", true
@@ -400,6 +405,20 @@ func getTLSPeerCert(cs *tls.ConnectionState) *x509.Certificate {
405
return cs.PeerCertificates[0]
406
}
407
408
+type requestID struct {
409
+ value string
410
+}
411
+
412
+// Lazy generates UUID string or return cached value if present
413
+func (rid *requestID) String() string {
414
+ if rid.value == "" {
415
+ if id, err := uuid.NewRandom(); err == nil {
416
+ rid.value = id.String()
417
+ }
418
+ }
419
+ return rid.value
420
+}
421
+
422
const (
423
reqCookieReplPrefix = "http.request.cookie."
424
reqHeaderReplPrefix = "http.request.header."