Commit 819d1cce authored by Michael Fraenkel's avatar Michael Fraenkel Committed by Brad Fitzpatrick

net/http: make LocalAddrContext handle wildcard interface

The LocalAddrContext should have the network address of the actual
interface.

Fixes #18686

Change-Id: I9c401eda312f3a0e7e65b013af827aeeef3b4d3d
Reviewed-on: https://go-review.googlesource.com/35490
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
parent d2863996
......@@ -4561,13 +4561,6 @@ func testServerContext_ServerContextKey(t *testing.T, h2 bool) {
if _, ok := got.(*Server); !ok {
t.Errorf("context value = %T; want *http.Server", got)
}
got = ctx.Value(LocalAddrContextKey)
if addr, ok := got.(net.Addr); !ok {
t.Errorf("local addr value = %T; want net.Addr", got)
} else if fmt.Sprint(addr) != r.Host {
t.Errorf("local addr = %v; want %v", addr, r.Host)
}
}))
defer cst.close()
res, err := cst.c.Get(cst.ts.URL)
......@@ -4577,6 +4570,37 @@ func testServerContext_ServerContextKey(t *testing.T, h2 bool) {
res.Body.Close()
}
func TestServerContext_LocalAddrContextKey_h1(t *testing.T) {
testServerContext_LocalAddrContextKey(t, h1Mode)
}
func TestServerContext_LocalAddrContextKey_h2(t *testing.T) {
testServerContext_LocalAddrContextKey(t, h2Mode)
}
func testServerContext_LocalAddrContextKey(t *testing.T, h2 bool) {
setParallel(t)
defer afterTest(t)
ch := make(chan interface{}, 1)
cst := newClientServerTest(t, h2, HandlerFunc(func(w ResponseWriter, r *Request) {
ch <- r.Context().Value(LocalAddrContextKey)
}))
defer cst.close()
if _, err := cst.c.Head(cst.ts.URL); err != nil {
t.Fatal(err)
}
host := cst.ts.Listener.Addr().String()
select {
case got := <-ch:
if addr, ok := got.(net.Addr); !ok {
t.Errorf("local addr value = %T; want net.Addr", got)
} else if fmt.Sprint(addr) != host {
t.Errorf("local addr = %v; want %v", addr, host)
}
case <-time.After(5 * time.Second):
t.Error("timed out")
}
}
// https://golang.org/issue/15960
func TestHandlerSetTransferEncodingChunked(t *testing.T) {
setParallel(t)
......
......@@ -1714,6 +1714,7 @@ func isCommonNetReadError(err error) bool {
// Serve a new connection.
func (c *conn) serve(ctx context.Context) {
c.remoteAddr = c.rwc.RemoteAddr().String()
ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
defer func() {
if err := recover(); err != nil && err != ErrAbortHandler {
const size = 64 << 10
......@@ -2680,7 +2681,6 @@ func (srv *Server) Serve(l net.Listener) error {
baseCtx := context.Background() // base is always background, per Issue 16220
ctx := context.WithValue(baseCtx, ServerContextKey, srv)
ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr())
for {
rw, e := l.Accept()
if e != nil {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment