如何在Golang中封装net.Conn.Read()函数

huangapple go评论71阅读模式
英文:

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

问题

我想封装Read函数net.Conn.Read()。目的是读取SSL握手消息。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{})

有什么方法可以实现吗?

提前感谢。

英文:

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

答案1

得分: 1

使用以下代码拦截net.Conn上的Read操作:

type wrap struct {
    // Conn是被包装的net.Conn。
    // 因为它是一个嵌入字段,net.Conn的方法会自动提升到wrap。
    net.Conn
}

// Read调用被包装的Read方法,并打印通过的字节。
// 将打印语句替换为适合你的应用程序的内容。
func (w wrap) Read(p []byte) (int, error) {
    n, err := w.Conn.Read(p)
    fmt.Printf("%x\n", p[:n]) // 示例
    return n, err
}

像这样进行包装

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

希望这能帮到你!

英文:

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

 type wrap {
     // 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{})

答案2

得分: -2

之前的回答确实完成了工作。

不过我建议你观看Liz Rice的演讲:GopherCon 2018: Liz Rice - Go程序员的安全连接指南

在她的Github上查看代码,你可能会找到更优雅的方法来实现你想要的功能。

客户端代码的第26行开始。

英文:

The previous answer gets the job done indeed.

However I would recommend Liz Rice's talk: GopherCon 2018: Liz Rice - The Go Programmer's Guide to Secure Connections

Going through her code in Github, you might find a more elegant way to achieve what you want.

Start with the client code on line 26.

huangapple
  • 本文由 发表于 2022年9月4日 11:57:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/73596694.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定