-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimestampheaders.go
More file actions
70 lines (60 loc) · 1.99 KB
/
timestampheaders.go
File metadata and controls
70 lines (60 loc) · 1.99 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
64
65
66
67
68
69
70
// Package traefikRequestTimestamps implements a Traefik plugin that adds timestamp headers to HTTP responses.
package traefikRequestTimestamps
import (
"context"
"net/http"
"time"
)
// Config holds the plugin configuration.
type Config struct {
RequestHeaderName string `json:"requestHeaderName,omitempty"`
ResponseHeaderName string `json:"responseHeaderName,omitempty"`
DateFormat string `json:"dateFormat,omitempty"`
}
// CreateConfig initializes the plugin configuration with default values.
func CreateConfig() *Config {
return &Config{
RequestHeaderName: "REQUEST-TIMESTAMP",
ResponseHeaderName: "RESPONSE-TIMESTAMP",
DateFormat: "2006-01-02T15:04:05.000Z",
}
}
// TimestampHeaders implements the Traefik plugin interface.
type TimestampHeaders struct {
next http.Handler
config *Config
}
// New creates a new TimestampHeaders plugin instance.
func New(_ context.Context, next http.Handler, config *Config, _ string) (http.Handler, error) {
return &TimestampHeaders{
next: next,
config: config,
}, nil
}
// responseWriter wraps http.ResponseWriter to add both timestamps
type responseWriter struct {
http.ResponseWriter
requestTimestamp string
headerWritten bool
config *Config
}
func (rw *responseWriter) WriteHeader(statusCode int) {
if !rw.headerWritten {
responseTimestamp := time.Now().UTC().Format(rw.config.DateFormat)
rw.Header().Set(rw.config.RequestHeaderName, rw.requestTimestamp)
rw.Header().Set(rw.config.ResponseHeaderName, responseTimestamp)
rw.headerWritten = true
}
rw.ResponseWriter.WriteHeader(statusCode)
}
func (t *TimestampHeaders) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
requestTimestamp := time.Now().UTC().Format(t.config.DateFormat)
// Wrap the response writer to add both timestamps when response is sent
wrappedWriter := &responseWriter{
ResponseWriter: rw,
requestTimestamp: requestTimestamp,
headerWritten: false,
config: t.config,
}
t.next.ServeHTTP(wrappedWriter, req)
}