2023-02-24 09:54:54 +08:00
|
|
|
package callback
|
|
|
|
|
|
|
|
import (
|
2023-04-01 20:56:49 +08:00
|
|
|
"github.com/Dreamacro/clash/common/buf"
|
|
|
|
N "github.com/Dreamacro/clash/common/net"
|
2023-02-24 09:54:54 +08:00
|
|
|
C "github.com/Dreamacro/clash/constant"
|
|
|
|
)
|
|
|
|
|
2023-04-01 20:56:49 +08:00
|
|
|
type firstWriteCallBackConn struct {
|
2023-02-24 09:54:54 +08:00
|
|
|
C.Conn
|
2023-04-01 20:56:49 +08:00
|
|
|
callback func(error)
|
2023-02-24 09:54:54 +08:00
|
|
|
written bool
|
|
|
|
}
|
|
|
|
|
2023-04-01 20:56:49 +08:00
|
|
|
func (c *firstWriteCallBackConn) Write(b []byte) (n int, err error) {
|
2023-02-24 09:54:54 +08:00
|
|
|
defer func() {
|
|
|
|
if !c.written {
|
|
|
|
c.written = true
|
2023-04-01 20:56:49 +08:00
|
|
|
c.callback(err)
|
2023-02-24 09:54:54 +08:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
return c.Conn.Write(b)
|
|
|
|
}
|
|
|
|
|
2023-04-02 22:24:46 +08:00
|
|
|
func (c *firstWriteCallBackConn) WriteBuffer(buffer *buf.Buffer) (err error) {
|
2023-04-01 20:56:49 +08:00
|
|
|
defer func() {
|
|
|
|
if !c.written {
|
|
|
|
c.written = true
|
|
|
|
c.callback(err)
|
|
|
|
}
|
|
|
|
}()
|
2023-04-02 22:24:46 +08:00
|
|
|
return c.Conn.WriteBuffer(buffer)
|
2023-04-01 20:56:49 +08:00
|
|
|
}
|
|
|
|
|
2023-04-02 22:24:46 +08:00
|
|
|
func (c *firstWriteCallBackConn) Upstream() any {
|
|
|
|
return c.Conn
|
2023-04-01 20:56:49 +08:00
|
|
|
}
|
|
|
|
|
2023-04-02 22:24:46 +08:00
|
|
|
var _ N.ExtendedConn = (*firstWriteCallBackConn)(nil)
|
2023-04-01 20:56:49 +08:00
|
|
|
|
|
|
|
func NewFirstWriteCallBackConn(c C.Conn, callback func(error)) C.Conn {
|
|
|
|
return &firstWriteCallBackConn{
|
|
|
|
Conn: c,
|
|
|
|
callback: callback,
|
|
|
|
written: false,
|
|
|
|
}
|
|
|
|
}
|