-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_id.go
More file actions
81 lines (68 loc) · 2.02 KB
/
request_id.go
File metadata and controls
81 lines (68 loc) · 2.02 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
71
72
73
74
75
76
77
78
79
80
81
package module
import (
"context"
"net/http"
"github.com/CrisisTextLine/modular"
"github.com/google/uuid"
)
type requestIDKey struct{}
// GetRequestID extracts the request ID from the context.
func GetRequestID(ctx context.Context) string {
if id, ok := ctx.Value(requestIDKey{}).(string); ok {
return id
}
return ""
}
// RequestIDMiddleware reads X-Request-ID header or generates a UUID,
// sets it on the context and response header.
type RequestIDMiddleware struct {
name string
headerName string
}
// NewRequestIDMiddleware creates a new RequestIDMiddleware.
func NewRequestIDMiddleware(name string) *RequestIDMiddleware {
return &RequestIDMiddleware{
name: name,
headerName: "X-Request-ID",
}
}
// Name returns the module name.
func (m *RequestIDMiddleware) Name() string {
return m.name
}
// Init registers the middleware as a service.
func (m *RequestIDMiddleware) Init(app modular.Application) error {
return nil
}
// Process implements the HTTPMiddleware interface.
func (m *RequestIDMiddleware) Process(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestID := r.Header.Get(m.headerName)
if requestID == "" {
requestID = uuid.New().String()
}
ctx := context.WithValue(r.Context(), requestIDKey{}, requestID)
w.Header().Set(m.headerName, requestID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// Middleware returns the HTTP middleware function.
func (m *RequestIDMiddleware) Middleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return m.Process(next)
}
}
// ProvidesServices returns the services provided by this module.
func (m *RequestIDMiddleware) ProvidesServices() []modular.ServiceProvider {
return []modular.ServiceProvider{
{
Name: m.name,
Description: "HTTP Request ID Middleware",
Instance: m,
},
}
}
// RequiresServices returns services required by this module.
func (m *RequestIDMiddleware) RequiresServices() []modular.ServiceDependency {
return nil
}