Obtain http.Request in http handler #1252
Unanswered
matejkramny
asked this question in
Q&A
Replies: 1 comment
-
You can define a package httputil
import (
"context"
"net/http"
)
type (
requestCtxKey struct{}
responseCtxKey struct{}
)
func InjectRequestToContext(next http.Handler) http.Handler {
f := func(w http.ResponseWriter, r *http.Request) {
r = r.WithContext(context.WithValue(r.Context(), requestCtxKey{}, r))
r = r.WithContext(context.WithValue(r.Context(), responseCtxKey{}, w))
next.ServeHTTP(w, r)
}
return http.HandlerFunc(f)
}
func RequestFromContext(ctx context.Context) *http.Request {
val := ctx.Value(requestCtxKey{})
return val.(*http.Request)
}
func ResponseFromContext(ctx context.Context) http.ResponseWriter {
val := ctx.Value(responseCtxKey{})
return val.(http.ResponseWriter)
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi there, is there a way to get the original http.Request object within the handler code?
I've scoured the docs and examples and can't find any way to get the request or any information about it. Am I missing something fundamental?
I'm trying to think ahead and might need to get the request headers, ip address or other things inside a handler.
Is there a good way to do this?
Thank you!
Matej
Beta Was this translation helpful? Give feedback.
All reactions