Last active
October 25, 2017 14:43
-
-
Save lamg/603e444180556b23049771a5856b6d9d to your computer and use it in GitHub Desktop.
How to get the IP address in the dialer's context, using https://github.com/elazarl/goproxy
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
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
gp "github.com/elazarl/goproxy" | |
"log" | |
"net" | |
"net/http" | |
) | |
func main() { | |
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout") | |
addr := flag.String("addr", ":8080", "proxy listen address") | |
flag.Parse() | |
px := gp.NewProxyHttpServer() | |
px.Verbose = *verbose | |
px.Tr.DialContext = dialHTTP | |
p := &proxy{px} | |
log.Fatal(http.ListenAndServe(*addr, p)) | |
} | |
type proxy struct { | |
px *gp.ProxyHttpServer | |
} | |
// RemoteAddr is the type to be used as key | |
// of RemoteAddr value in context | |
type RemoteAddr string | |
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
q := r.WithContext(context.WithValue(context.Background(), | |
RemoteAddr("RemoteAddress"), r.RemoteAddr)) | |
p.px.ServeHTTP(w, q) | |
} | |
func dialHTTP(c context.Context, nt, ad string) (n net.Conn, e error) { | |
v := c.Value(RemoteAddr("RemoteAddress")) | |
fmt.Printf("%v\n", v) | |
n, e = net.Dial(nt, ad) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment