github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/net/netapi/proxy.go (about) 1 package netapi 2 3 import ( 4 "context" 5 "net" 6 "sync" 7 ) 8 9 type EmptyDispatch struct{} 10 11 func (EmptyDispatch) Dispatch(_ context.Context, a Address) (Address, error) { return a, nil } 12 13 type errProxy struct { 14 EmptyDispatch 15 error 16 } 17 18 func NewErrProxy(err error) Proxy { return &errProxy{error: err} } 19 func (e errProxy) Conn(context.Context, Address) (net.Conn, error) { return nil, e.error } 20 func (e errProxy) PacketConn(context.Context, Address) (net.PacketConn, error) { return nil, e.error } 21 22 type DynamicProxy struct { 23 mu sync.RWMutex 24 p Proxy 25 } 26 27 func (d *DynamicProxy) Conn(ctx context.Context, a Address) (net.Conn, error) { 28 d.mu.RLock() 29 defer d.mu.RUnlock() 30 return d.p.Conn(ctx, a) 31 } 32 33 func (d *DynamicProxy) PacketConn(ctx context.Context, a Address) (net.PacketConn, error) { 34 d.mu.RLock() 35 defer d.mu.RUnlock() 36 return d.p.PacketConn(ctx, a) 37 } 38 39 func (d *DynamicProxy) Dispatch(ctx context.Context, a Address) (Address, error) { 40 d.mu.RLock() 41 defer d.mu.RUnlock() 42 return d.p.Dispatch(ctx, a) 43 } 44 45 func (d *DynamicProxy) Set(p Proxy) { 46 d.mu.Lock() 47 defer d.mu.Unlock() 48 d.p = p 49 } 50 51 func NewDynamicProxy(p Proxy) *DynamicProxy { return &DynamicProxy{p: p} }