Add cancel API and support used by other package
perqin opened this issue · comments
Perqin commented
I am trying to write a Shadowsocks GUI app with go, and this package is added as the dependency. But for now, public API to start and stop an instance is not supported yet. It simply starts some goroutines and terminates the program on receiving interrupt signal. I try to refactor them to support cancellation, so that I can start and stop and restart Shadowsocks instance in my app. For example, refactor from:
func udpLocal(laddr, server, target string, shadow func(net.PacketConn) net.PacketConn) {
// ...
for {
n, raddr, err := c.ReadFrom(buf[len(tgt):])
// ...
}
}
to:
func udpLocal(ctx context.Context, laddr, server, target string, shadow func(net.PacketConn) net.PacketConn) {
// ...
var canceled bool
go func() {
<-ctx.Done()
canceled = true
c.Close()
}()
logf("UDP tunnel %s <-> %s <-> %s", laddr, server, target)
for {
if canceled {
break
}
n, raddr, err := c.ReadFrom(buf[len(tgt):])
// ...
}
}
But I am not familiar with go, and is not sure whether this is the proper solution. Could you give me some advice?