大猩猩websocket – closeHandler链

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

gorilla websocket - chain of closeHandler

问题

在gorilla websocket中,websocket.Conn结构体有一个名为SetCloseHandler()的方法,用于设置连接的关闭处理程序。如果传递的处理程序为nil,它将使用默认处理程序。

我想保留默认处理程序,但在默认处理程序之前或之后执行其他操作。

也就是说,我想要一个处理程序链,例如:

  • prependCloseHandler(h)
    在处理程序链的开头添加一个处理程序。
  • appendCloseHandler(h)
    在处理程序链的末尾添加一个处理程序。

然后,处理程序链中的每个处理程序将按顺序执行。

有没有办法做到这一点,而不需要将默认处理程序复制为我的新处理程序的一部分?

谢谢。

英文:

In gorilla websocket, websocket.Conn struct has a method SetCloseHandler(), which set close handler of the connection.
If the passed handler is nil, it uses a default handler.

I wan't to keep the default handler, but do something else before or after the default handler.

Aka. a handler chain, e.g. some method like:

  • prependCloseHandler(h)
    which add a handler at beginning of handler chain.
  • appendCloseHandler(h)
    which add a handler at end of handler chain.

Then each handler in the chain will be executed in order.

Is there anyway to do that, without coping the default handler as part of my new handler?

Thanks.

答案1

得分: 2

该包没有直接提供一种在 close message 前面或后面添加处理程序的机制。使用以下函数作为您的函数的起点:

closeHandler := conn.CloseHandler()
conn.SetCloseHandler(func(code int, text string) error {
    // 在这里添加您的代码...
    err := closeHandler(code, text)
    // ... 或者在这里添加代码。
    return err
})

请注意,当从对等方接收到关闭消息时,将调用关闭处理程序,而不是在连接关闭时调用。大多数应用程序应该使用默认处理程序即可。

英文:

The package does not provide a direct mechanism for prepending or appending a handler for a close message. Use this function as a starter for your function:

closeHandler := conn.CloseHandler()
conn.SetCloseHandler(func(code int, text string) error {
	// Add your code here ...
	err := closeHandler(code, text)
	// ... or here.
	return err
})

Note that the close handler is called when a close message is received from the peer, not when the connection is closed. Most applications should be good with the default handler.

huangapple
  • 本文由 发表于 2022年1月27日 11:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/70872838.html
匿名

发表评论

匿名网友

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

确定