Skip to content

Instantly share code, notes, and snippets.

@nickvanw
Created April 10, 2015 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickvanw/7906774433e00ca7e5b0 to your computer and use it in GitHub Desktop.
Save nickvanw/7906774433e00ca7e5b0 to your computer and use it in GitHub Desktop.
// WithUUID returns a new Context that carries a uuid. If the UUID
// already exists, nothing is done. Otherwise a new one is created.
func WithUUID(c context.Context) (context.Context, string) {
if u, ok := c.Value("request.id").(string); ok {
return c, u
}
uuid := uuid.New()
return context.WithValue(c, "request.id", uuid), uuid
}
// FromRequest retrieves or creates a UUID from the request and
// accordingly sets the request.id of context.
func FromRequest(c context.Context, req *http.Request) context.Context {
headers := req.Header.Get("Request-Id")
if headers != "" {
return context.WithValue(c, "request.id", headers)
}
c, _ = WithUUID(c)
return c
}
// WithLog retrieves or create a UUID for the context and sets
// a field for it in the log entry.
func WithLog(c context.Context, ll *log.Entry) *log.Entry {
_, uuid := WithUUID(c)
return ll.WithFields(log.Fields{"request.id": uuid})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment