Is there any option to get current request object (struct) outside http.HandlerFunc? I'm facing problem that I need unique random hash per request only, I can't use global variable because in case my application will handle 2 or more requests at the same time, each request will override global variable value.
I figured out that I can use context like this:
func Init() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
ctx := context.WithValue(request.Context(), "requestId", GetRequestHash())
next.ServeHTTP(writer, request.WithContext(ctx))
})
}
}
Then in HandlerFunc I can get this unique hash
request.Context().Value("requestId")
but the problem is that I need this value very very deep down my application and I can't just pass this hash by parameter. I have many handlers already written and this handlers calls function that calls another... I need something like http.GetCurrentRequest
somewhere outside the HandlerFunc to get request context and finally to get requestId (unique hash per request).
Obviously I can not just save this hash value as global variable because it will be overriden by other request...