Skip to content

Commit

Permalink
feat: include RemoteAddress ctx wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
jeroenrinzema committed Nov 11, 2024
1 parent db7be29 commit c7ee52b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
17 changes: 17 additions & 0 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package wire

import (
"context"
"net"

"github.com/jackc/pgx/v5/pgtype"
)
Expand All @@ -12,6 +13,7 @@ const (
ctxTypeMap ctxKey = iota
ctxClientMetadata
ctxServerMetadata
ctxRemoteAddr
)

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

func setRemoteAddress(ctx context.Context, addr net.Addr) context.Context {
return context.WithValue(ctx, ctxRemoteAddr, addr)
}

// RemoteAddress returns the Postgres remote address connection info if it has been set inside
// the given context.
func RemoteAddress(ctx context.Context) net.Addr {
val := ctx.Value(ctxRemoteAddr)
if val == nil {
return nil
}

return val.(net.Addr)
}

// Parameters represents a parameters collection of parameter status keys and
// their values
type Parameters map[ParameterStatus]string
Expand Down
3 changes: 1 addition & 2 deletions wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,12 @@ func (srv *Server) Serve(listener net.Listener) error {

func (srv *Server) serve(ctx context.Context, conn net.Conn) error {
ctx = setTypeInfo(ctx, srv.types)
ctx = context.WithValue(ctx, "remote_addr", conn.RemoteAddr())
ctx = setRemoteAddress(ctx, conn.RemoteAddr())
defer conn.Close()

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

conn, version, reader, err := srv.Handshake(conn)

if err != nil {
return err
}
Expand Down

0 comments on commit c7ee52b

Please sign in to comment.