2017-11-04 17:33
浏览 262


I am interacting with an http client API which accepts a *tls.Conn. I cannot change the API. I want some code to be executed when the connection is closed, but I don't see a way to do this. If I create a struct which embeds a *tls.Conn and I "override" Close(), the API won't accept the struct because go only follows the sub-type is-a relationship with interfaces - tls.Conn is not an interface.

Is there any way to get around this - is there some standard hook I can use to be notified when the client connection is closed?

图片转代码服务由CSDN问答提供 功能建议

我正在与接受 * tls.Conn 。 我无法更改API。 我希望在关闭连接时执行一些代码,但是我看不到这样做的方法。 如果我创建了一个嵌入 * tls.Conn 的结构,并且“覆盖”了 Close(),则该API将不会接受该结构,因为go仅遵循该子结构, 类型是-与接口的关系- tls.Conn 不是接口。

有没有办法解决这个问题- 客户端连接关闭时,是否可以使用一些标准的钩子通知我?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dthh5038 2017-11-05 00:14

    If you're using tls.Client to construct the *tls.Conn then you can wrap the first argument to achieve your goal.

    type CloseListener struct {
        net.Conn // embed the original conn
    func (c *CloseListener) Close() error {
        err := c.Conn.Close()
        // ... do your stuff ...
        return err
    conn := tls.Client(&CloseListener{c}, &tls.Config{ /* ... */ }) 

    If you look at how tls.Conn's Close is implemented you'll see that it should call your Close implementation unless there was some error.

    解决 无用
    打赏 举报

相关推荐 更多相似问题