Skip to content

Commit

Permalink
net/http: provide access to the listener address an HTTP request arri…
Browse files Browse the repository at this point in the history
…ved on

This adds a context key named LocalAddrContextKey (for now, see #15229) to
let users access the net.Addr of the net.Listener that accepted the connection
that sent an HTTP request. This is similar to ServerContextKey which provides
access to the *Server. (A Server may have multiple Listeners)

Fixes #6732

Change-Id: I74296307b68aaaab8df7ad4a143e11b5227b5e62
Reviewed-on: https://go-review.googlesource.com/22672
Reviewed-by: Andrew Gerrand <adg@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
  • Loading branch information
bradfitz committed May 1, 2016
1 parent abc1472 commit a9cf0b1
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/net/http/serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4062,7 +4062,12 @@ func TestServerContext_ServerContextKey(t *testing.T) {
ctx := r.Context()
got := ctx.Value(ServerContextKey)
if _, ok := got.(*Server); !ok {
t.Errorf("context value = %T; want *http.Server")
t.Errorf("context value = %T; want *http.Server", got)
}

got = ctx.Value(LocalAddrContextKey)
if _, ok := got.(net.Addr); !ok {
t.Errorf("local addr value = %T; want net.Addr", got)
}
}))
defer ts.Close()
Expand Down
7 changes: 7 additions & 0 deletions src/net/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,12 @@ var (
// started the handler. The associated value will be of
// type *Server.
ServerContextKey = &contextKey{"http-server"}

// LocalAddrContextKey is a context key. It can be used in
// HTTP handlers with context.WithValue to access the address
// the local address the connection arrived on.
// The associated value will be of type net.Addr.
LocalAddrContextKey = &contextKey{"local-addr"}
)

// A conn represents the server side of an HTTP connection.
Expand Down Expand Up @@ -2189,6 +2195,7 @@ func (srv *Server) Serve(l net.Listener) error {
// use cases yet.
baseCtx := context.Background()
ctx := context.WithValue(baseCtx, ServerContextKey, srv)
ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr())
for {
rw, e := l.Accept()
if e != nil {
Expand Down

0 comments on commit a9cf0b1

Please sign in to comment.