Use request IDs and audit logs
Use request IDs and audit logs
A request ID helps correlate records from one request across services. An audit event records who did what, to which resource, when and with what outcome; a request ID alone is not an audit trail. Generate a server-side ID or accept one only from a trusted upstream with a bounded format. Propagate it through request context and response metadata. Never use it as proof of identity.
package main
import ( "context" "fmt" "net/http" "net/http/httptest")
type reqKey struct{}
func main() { r := httptest.NewRequest("GET", "/books/7", nil) r = r.WithContext(context.WithValue(r.Context(), reqKey{}, "lab-17")) h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { id, ok := r.Context().Value(reqKey{}).(string) if !ok { w.WriteHeader(500) return } w.Header().Set("X-Request-ID", id) w.WriteHeader(204) }) w := httptest.NewRecorder() h.ServeHTTP(w, r) fmt.Println(w.Code, w.Header().Get("X-Request-ID"))}A distinct context key type avoids collisions with ordinary string keys. The fixed ID is only a deterministic fixture, not a generator. Production IDs need suitable uniqueness across instances and a validated length and character policy. Preserve the request context rather than replacing it with Background, so cancellation still propagates.
Expected output:
204 lab-17Log a minimal structured event
package main
import ( "encoding/json" "fmt")
type Event struct { RequestID string `json:"request_id"` Actor string `json:"actor"` Action string `json:"action"` Status int `json:"status"`}
func audit(e Event) string { b, err := json.Marshal(e) if err != nil { panic(err) } return string(b)}func main() { fmt.Println(audit(Event{"lab-17", "u1", "book.read", 200}))}Choose explicit fields instead of logging all headers or bodies. JSON encoding escapes control characters in strings; never include bearer credentials, passwords or sensitive payloads. The small fixture lacks timestamp and resource ID; a real audit schema also records these, protects integrity and access, defines retention and handles delivery failures. Log denied operations where policy requires them. Use a protected sink, not the public response.
Expected output:
{"request_id":"lab-17","actor":"u1","action":"book.read","status":200}Try it locally
Create an audit event for lab-18, actor u2, action book.delete, status 403. Print the JSON; no headers or body may appear.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 07: Use request IDs and audit logs
Check the lesson objective before moving on.
What should a request ID prove?
What is a safer audit schema?