Accessing the Underlying Socket of a net/http Response in Go
Introduction
While developing a web application using Go's net/http package, it might be necessary to access the underlying socket associated with an HTTP response. This allows for the execution of additional platform-specific operations on the socket, such as TCP_INFO system calls.
Solutions
Using Request Context (Go 1.13 and later)
In Go 1.13 and later, the net.Conn object can be stored in the Request Context, enabling easy access within the handler function.
<code class="go">func GetConn(r *http.Request) (net.Conn) { return r.Context().Value(ConnContextKey).(net.Conn) }</code>
Using RemoteAddr and Connections Map (Pre-Go 1.13)
For servers listening on TCP ports, a unique key can be generated from the RemoteAddr of each connection using a global map.
<code class="go">func GetConn(r *http.Request) (net.Conn) { return conns[r.RemoteAddr] }</code>
Overriding RemoteAddr for UNIX Socket
For servers listening on UNIX sockets, the RemoteAddr is always "@", making the previous approach ineffective. To resolve this, override net.Listener.Accept() and redefine the RemoteAddr() method.
<code class="go">type remoteAddrPtrConn struct { net.Conn ptrStr string } func (self remoteAddrPtrConn) RemoteAddr() (net.Addr) { return remoteAddrPtr{self.ptrStr} }</code>
Additional Notes
The above is the detailed content of How to Access the Underlying Socket of a net/http Response in Go?. For more information, please follow other related articles on the PHP Chinese website!