github.com/metacubex/mihomo@v1.18.5/common/callback/callback.go (about)

     1  package callback
     2  
     3  import (
     4  	"github.com/metacubex/mihomo/common/buf"
     5  	N "github.com/metacubex/mihomo/common/net"
     6  	C "github.com/metacubex/mihomo/constant"
     7  )
     8  
     9  type firstWriteCallBackConn struct {
    10  	C.Conn
    11  	callback func(error)
    12  	written  bool
    13  }
    14  
    15  func (c *firstWriteCallBackConn) Write(b []byte) (n int, err error) {
    16  	defer func() {
    17  		if !c.written {
    18  			c.written = true
    19  			c.callback(err)
    20  		}
    21  	}()
    22  	return c.Conn.Write(b)
    23  }
    24  
    25  func (c *firstWriteCallBackConn) WriteBuffer(buffer *buf.Buffer) (err error) {
    26  	defer func() {
    27  		if !c.written {
    28  			c.written = true
    29  			c.callback(err)
    30  		}
    31  	}()
    32  	return c.Conn.WriteBuffer(buffer)
    33  }
    34  
    35  func (c *firstWriteCallBackConn) Upstream() any {
    36  	return c.Conn
    37  }
    38  
    39  func (c *firstWriteCallBackConn) WriterReplaceable() bool {
    40  	return c.written
    41  }
    42  
    43  func (c *firstWriteCallBackConn) ReaderReplaceable() bool {
    44  	return true
    45  }
    46  
    47  var _ N.ExtendedConn = (*firstWriteCallBackConn)(nil)
    48  
    49  func NewFirstWriteCallBackConn(c C.Conn, callback func(error)) C.Conn {
    50  	return &firstWriteCallBackConn{
    51  		Conn:     c,
    52  		callback: callback,
    53  		written:  false,
    54  	}
    55  }