forked from EasySolutionsIO/traefikxrequeststart
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraefik_x_request_start.go
More file actions
63 lines (54 loc) · 1.4 KB
/
traefik_x_request_start.go
File metadata and controls
63 lines (54 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Package traefikxrequeststart adds X-Request-Start header in "t=<seconds.millis>" format.
package traefikxrequeststart
import (
"context"
"fmt"
"net/http"
"time"
)
type Config struct {
// Optional: override header name and include "t=" prefix
HeaderName string
WithPrefix bool
}
func CreateConfig() *Config {
return &Config{
HeaderName: "X-Request-Start",
WithPrefix: true, // matches common NGINX/Heroku style: "t=<value>"
}
}
type XRequestStart struct {
next http.Handler
name string
headerName string
withPrefix bool
}
func New(_ context.Context, next http.Handler, cfg *Config, name string) (http.Handler, error) {
if cfg == nil {
cfg = CreateConfig()
}
return &XRequestStart{
next: next,
name: name,
headerName: cfg.HeaderName,
withPrefix: cfg.WithPrefix,
}, nil
}
func (a *XRequestStart) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
val := makeUnixSecMillis(time.Now())
if a.withPrefix {
val = "t=" + val
}
// Forward to backend
req.Header.Set(a.headerName, val)
// Also expose on response (handy for debugging/clients)
rw.Header().Set(a.headerName, val)
a.next.ServeHTTP(rw, req)
}
// makeUnixSecMillis returns "seconds.mmm" (UTC) with millisecond precision.
func makeUnixSecMillis(t time.Time) string {
t = t.UTC()
sec := t.Unix()
msec := t.Nanosecond() / int(time.Millisecond) // 0..999
return fmt.Sprintf("%d.%03d", sec, msec)
}