Created
April 10, 2015 18:21
-
-
Save nickvanw/7906774433e00ca7e5b0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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