Skip to content

Instantly share code, notes, and snippets.

@lamg
Last active October 25, 2017 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lamg/603e444180556b23049771a5856b6d9d to your computer and use it in GitHub Desktop.
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
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