// Package observe carries per-request observations from the handlers that // make them to the logging and metrics middleware, through the request // context. It holds only bounded values, never request data. package observe import "context" // Request collects what handlers report about one request. The handler // chain of a request runs on one goroutine, so it needs no lock. type Request struct { problemCode string } type requestKey struct{} // Ensure returns ctx with a Request, reusing the one ctx already carries, so // every middleware of a request sees the same observations. func Ensure(ctx context.Context) (context.Context, *Request) { if current, ok := ctx.Value(requestKey{}).(*Request); ok { return ctx, current } current := &Request{} return context.WithValue(ctx, requestKey{}, current), current } // RecordProblem notes the problem code of the response to the request of // ctx. The code must come from the closed problem catalogue. Without a // Request in ctx it does nothing. func RecordProblem(ctx context.Context, code string) { if current, ok := ctx.Value(requestKey{}).(*Request); ok { current.problemCode = code } } // ProblemCode returns the recorded problem code, or empty when the handlers // recorded none. func (request *Request) ProblemCode() string { return request.problemCode }