-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathserver.go
More file actions
57 lines (45 loc) · 1.06 KB
/
server.go
File metadata and controls
57 lines (45 loc) · 1.06 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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
)
type requestContextKey struct{}
type requestContextValue struct {
requestID string
}
func addRequestID(r *http.Request, requestID string) *http.Request {
c := requestContextValue{
requestID: requestID,
}
currentCtx := r.Context()
newCtx := context.WithValue(currentCtx, requestContextKey{}, c)
return r.WithContext(newCtx)
}
func logRequest(r *http.Request) {
ctx := r.Context()
v := ctx.Value(requestContextKey{})
if m, ok := v.(requestContextValue); ok {
log.Printf("Processing request: %s", m.requestID)
}
}
func processRequest(w http.ResponseWriter, r *http.Request) {
logRequest(r)
fmt.Fprintf(w, "Request processed")
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
requestID := "request-123-abc"
r = addRequestID(r, requestID)
processRequest(w, r)
}
func main() {
listenAddr := os.Getenv("LISTEN_ADDR")
if len(listenAddr) == 0 {
listenAddr = ":8080"
}
mux := http.NewServeMux()
mux.HandleFunc("/api", apiHandler)
log.Fatal(http.ListenAndServe(listenAddr, mux))
}