Skip to content

Commit bb11a1b

Browse files
Add remote_addr to context (#70)
* Add remote_addr to context * feat: include RemoteAddress ctx wrapper --------- Co-authored-by: Jeroen Rinzema <[email protected]>
1 parent f85f855 commit bb11a1b

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

conn.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package wire
22

33
import (
44
"context"
5+
"net"
56

67
"github.com/jackc/pgx/v5/pgtype"
78
)
@@ -12,6 +13,7 @@ const (
1213
ctxTypeMap ctxKey = iota
1314
ctxClientMetadata
1415
ctxServerMetadata
16+
ctxRemoteAddr
1517
)
1618

1719
// setTypeInfo constructs a new Postgres type connection info for the given value
@@ -30,6 +32,21 @@ func TypeMap(ctx context.Context) *pgtype.Map {
3032
return val.(*pgtype.Map)
3133
}
3234

35+
func setRemoteAddress(ctx context.Context, addr net.Addr) context.Context {
36+
return context.WithValue(ctx, ctxRemoteAddr, addr)
37+
}
38+
39+
// RemoteAddress returns the Postgres remote address connection info if it has been set inside
40+
// the given context.
41+
func RemoteAddress(ctx context.Context) net.Addr {
42+
val := ctx.Value(ctxRemoteAddr)
43+
if val == nil {
44+
return nil
45+
}
46+
47+
return val.(net.Addr)
48+
}
49+
3350
// Parameters represents a parameters collection of parameter status keys and
3451
// their values.
3552
type Parameters map[ParameterStatus]string

wire.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ func (srv *Server) Serve(listener net.Listener) error {
123123

124124
func (srv *Server) serve(ctx context.Context, conn net.Conn) error {
125125
ctx = setTypeInfo(ctx, srv.types)
126+
ctx = setRemoteAddress(ctx, conn.RemoteAddr())
126127
defer conn.Close()
127128

128129
srv.logger.Debug("serving a new client connection")

0 commit comments

Comments
 (0)