From ed75b79764a4b666debc2a408499a14dc776fd16 Mon Sep 17 00:00:00 2001 From: kehiy Date: Sun, 15 Sep 2024 13:43:07 +0330 Subject: [PATCH] feat:(conn): add RemoteAddr method --- accept.go | 1 + conn.go | 8 ++++++++ internal/examples/echo/server.go | 2 ++ 3 files changed, 11 insertions(+) diff --git a/accept.go b/accept.go index 774ea285..313290f3 100644 --- a/accept.go +++ b/accept.go @@ -156,6 +156,7 @@ func accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (_ *Con client: false, copts: copts, flateThreshold: opts.CompressionThreshold, + remoteAddr: r.RemoteAddr, br: brw.Reader, bw: brw.Writer, diff --git a/conn.go b/conn.go index d7434a9d..c5a30e5a 100644 --- a/conn.go +++ b/conn.go @@ -49,6 +49,7 @@ type Conn struct { client bool copts *compressionOptions flateThreshold int + remoteAddr string br *bufio.Reader bw *bufio.Writer @@ -88,6 +89,7 @@ type connConfig struct { client bool copts *compressionOptions flateThreshold int + remoteAddr string br *bufio.Reader bw *bufio.Writer @@ -100,6 +102,7 @@ func newConn(cfg connConfig) *Conn { client: cfg.client, copts: cfg.copts, flateThreshold: cfg.flateThreshold, + remoteAddr: cfg.remoteAddr, br: cfg.br, bw: cfg.bw, @@ -192,6 +195,11 @@ func (c *Conn) flate() bool { return c.copts != nil } +// RemoteAddr returns the remote address of websocket connection. +func (c *Conn) RemoteAddr() string { + return c.remoteAddr +} + // Ping sends a ping to the peer and waits for a pong. // Use this to measure latency or ensure the peer is responsive. // Ping must be called concurrently with Reader as it does diff --git a/internal/examples/echo/server.go b/internal/examples/echo/server.go index 37e2f2c4..5f83b8b7 100644 --- a/internal/examples/echo/server.go +++ b/internal/examples/echo/server.go @@ -30,6 +30,8 @@ func (s echoServer) ServeHTTP(w http.ResponseWriter, r *http.Request) { } defer c.CloseNow() + s.logf("new incoming connection: %s", c.RemoteAddr()) + if c.Subprotocol() != "echo" { c.Close(websocket.StatusPolicyViolation, "client must speak the echo subprotocol") return