Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add access to http.Request object in Marshaled() #82

Closed
oryband opened this issue Oct 19, 2014 · 3 comments
Closed

Add access to http.Request object in Marshaled() #82

oryband opened this issue Oct 19, 2014 · 3 comments

Comments

@oryband
Copy link

oryband commented Oct 19, 2014

I need to access the remote address in a marshaled function, and for this I need access to the http.Request object. Currently there's no obvious way to do that. Am I missing something? Will be happy for any guidance if there is an easy way to do so. Otherwise, please add this option. Will be happy to do that myself and pull request if you'll guide me first.

@oryband
Copy link
Author

oryband commented Nov 3, 2014

I eventually managed to do that, but it took me a very long time because of missing documentation. What I did was this:

tigertonic.WithContext(
    // Create context for handler.
    tigertonic.If(createContext, tigertonic.Marshaled(collect)),
RequestContext{}))

// http.Handler which injects IP address and other necessary data to request
// context.  Data is passed on to Marshalled(collect).
func createContext(r *http.Request) (http.Header, error) { /*...*/ }

type RequestContext struct { /*...*/ }

I'm still not sure this is the most straightforward way to do that. Documentation should be more verbose.

@rcrowley
Copy link
Owner

rcrowley commented Nov 8, 2014

You know, I never considered a handler that requires access to http.Request.RemoteAddr. In every production situation I've encountered that information's meaningless and the real remote address comes via the X-Forwarded-For header.

So a shorter way to get what you're after might be something like this (written off-the-cuff and not tested):

func xForwardedFor(handler http.Handler) http.Handler {
    return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
        if r.Header.Get("X-Forwarded-For") == "" {
            r.Header.Set("X-Forwarded-For", r.RemoteAddr)
        }
        handler.ServeHTTP(w, r)
    }
}

@oryband
Copy link
Author

oryband commented Nov 10, 2014

@rcrowley that's what I did in the first place, but then I started noticing we're receiving requests without X-Forwarder-For header. So, we had to add a fallback to fetch the IP from the request object.

Is my solution optimal? Or could I have done it better?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants