-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
50 lines (39 loc) · 1.16 KB
/
http.go
File metadata and controls
50 lines (39 loc) · 1.16 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
package logger
import (
"context"
"io"
"net/http"
"time"
)
const (
headerKeyLogParentId = "X-Log-Parent-Id"
)
func HttpMiddleware() func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
logParentId := r.Header.Get(headerKeyLogParentId)
if logParentId == "" {
logParentId = newId()
}
ctx := setLogParentId(r.Context(), logParentId)
ctx = Info(ctx, "received http request", "method", r.Method, "url", r.URL.String())
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
Info(ctx, "finished http request", "duration", time.Since(start).String())
})
}
}
func NewHttpRequest(ctx context.Context, method string, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return nil, err
}
HttpUpdateRequest(req)
return req, nil
}
// HttpUpdateRequest updates the http request with the log parent id added to the header
func HttpUpdateRequest(r *http.Request) {
parentId := getLogParentId(r.Context())
r.Header.Set(headerKeyLogParentId, parentId)
}