Skip to content
Discussion options

You must be logged in to vote

@davidolrik - how do you get access to the http.request from huma.Context?

What I did, was creating a small middleware that added the client ip from request to the context like this:

type CtxClientIP struct{}

func HumaMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r = r.WithContext(context.WithValue(r.Context(), CtxClientIP{}, r.RemoteAddr))
		next.ServeHTTP(w, r)
	})
}

You can then access the client ip in your request handlers like so:

ip := ctx.Value(CtxClientIP{}).(string)

If you need access to the whole request, then just put r in to the context

Replies: 2 comments 5 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
5 replies
@x-user
Comment options

@davidolrik
Comment options

@joa23
Comment options

@davidolrik
Comment options

Answer selected by davidolrik
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
4 participants