Search code examples
gossl

How to wrap net.Conn.Read() in Golang


I want to wrap Read function net.Conn.Read(). The purpose of this to read the SSL handshake messages. https://pkg.go.dev/net#TCPConn.Read

nc, err := net.Dial("tcp", "google.com:443")
if err != nil {
    fmt.Println(err)
}
tls.Client(nc, &tls.Config{})

Are there any ways to do?

Thanks in advance


Solution

  • Use the following code to intercept Read on a net.Conn:

     type wrap struct {
         // Conn is the wrapped net.Conn.
         // Because it's an embedded field, the 
         // net.Conn methods are automatically promoted
         // to wrap.
         net.Conn 
     }
    
     // Read calls through to the wrapped read and
     // prints the bytes that flow through. Replace
     // the print statement with whatever is appropriate
     // for your application.
     func (w wrap) Read(p []byte) (int, error) {
         n, err := w.Conn.Read()
         fmt.Printf("%x\n", p[:n]) // example
         return n, err
     }
    

    Wrap like this:

     tnc, err :=tls.Client(wrap{nc}, &tls.Config{})