-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
95 lines (80 loc) · 2.54 KB
/
Copy pathmain.go
File metadata and controls
95 lines (80 loc) · 2.54 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"log/slog"
"math/rand"
"net/http"
"net/http/httputil"
"net/url"
"time"
"github.com/0xPolygon/requestid"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httplog/v2"
"github.com/go-chi/transport"
)
func main() {
// Set Request-Id on all outgoing HTTP requests globally.
http.DefaultTransport = transport.Chain(
http.DefaultTransport,
transport.SetHeader("User-Agent", "my-app/v1.0.0"),
requestid.Transport,
)
// Send test request.
go func() {
time.Sleep(time.Millisecond * time.Duration(rand.Intn(800)+200))
req, _ := http.NewRequest("GET", "http://localhost:3333/proxy/proxy", nil)
_, _ = http.DefaultClient.Do(req)
}()
// HTTP server with Request-Id middleware + logging.
r := chi.NewRouter()
r.Use(requestid.Middleware)
r.Use(httplog.RequestLogger(logger()))
r.Use(middleware.Recoverer)
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// Log requestId to request logger.
id := requestid.FromContext(r.Context())
httplog.LogEntrySetField(ctx, "requestId", slog.StringValue(id))
next.ServeHTTP(w, r.WithContext(ctx))
})
})
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(requestid.FromContext(r.Context())))
})
r.Get("/proxy", func(w http.ResponseWriter, r *http.Request) {
reverseProxyTo, _ := url.Parse("http://localhost:3333")
r.URL.Path = "/"
proxy := httputil.NewSingleHostReverseProxy(reverseProxyTo)
proxy.ServeHTTP(w, r)
})
r.Get("/proxy/proxy", func(w http.ResponseWriter, r *http.Request) {
reverseProxyTo, _ := url.Parse("http://localhost:3333")
r.URL.Path = "/proxy"
proxy := httputil.NewSingleHostReverseProxy(reverseProxyTo)
proxy.ServeHTTP(w, r)
})
fmt.Println(`Try sending a sample request in another terminal and see Request-Id propagation:`)
fmt.Println(`$ curl http://localhost:3333/proxy/proxy`)
fmt.Println(`$ curl -H "Request-Id: req_01kmfjypewe1wrfeb01wjfxand" http://localhost:3333/proxy/proxy`)
fmt.Println()
fmt.Println(`server listening on :3333`)
http.ListenAndServe(":3333", r)
}
func logger() *httplog.Logger {
return httplog.NewLogger("httplog-example", httplog.Options{
LogLevel: slog.LevelDebug,
RequestHeaders: false,
ResponseHeaders: false,
JSON: false,
Concise: true,
MessageFieldName: "message",
LevelFieldName: "severity",
TimeFieldFormat: time.RFC3339,
Tags: map[string]string{
"version": "v0.1.0",
"env": "dev",
},
})
}