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

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

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

问题

我想封装Read函数net.Conn.Read()。目的是读取SSL握手消息。https://pkg.go.dev/net#TCPConn.Read

  1. nc, err := net.Dial("tcp", "google.com:443")
  2. if err != nil {
  3. fmt.Println(err)
  4. }
  5. 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

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

Are there any ways to do?

Thanks in advance

答案1

得分: 1

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

  1. type wrap struct {
  2. // Conn是被包装的net.Conn。
  3. // 因为它是一个嵌入字段,net.Conn的方法会自动提升到wrap。
  4. net.Conn
  5. }
  6. // Read调用被包装的Read方法,并打印通过的字节。
  7. // 将打印语句替换为适合你的应用程序的内容。
  8. func (w wrap) Read(p []byte) (int, error) {
  9. n, err := w.Conn.Read(p)
  10. fmt.Printf("%x\n", p[:n]) // 示例
  11. return n, err
  12. }
  13. 像这样进行包装
  14. tnc, err := tls.Client(wrap{nc}, &tls.Config{})

希望这能帮到你!

英文:

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

  1. type wrap {
  2. // Conn is the wrapped net.Conn.
  3. // Because it's an embedded field, the
  4. // net.Conn methods are automatically promoted
  5. // to wrap.
  6. net.Conn
  7. }
  8. // Read calls through to the wrapped read and
  9. // prints the bytes that flow through. Replace
  10. // the print statement with whatever is appropriate
  11. // for your application.
  12. func (w wrap) Read(p []byte) (int, error) {
  13. n, err := w.Conn.Read()
  14. fmt.Printf("%x\n", p[:n]) // example
  15. return n, err
  16. }

Wrap like this:

  1. 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:

确定