shadowsocks / go-shadowsocks2

Modern Shadowsocks in Go
Apache License 2.0
4.45k stars 1.39k forks source link

Add cancel API and support used by other package #163

Open perqin opened 4 years ago

perqin commented 4 years ago

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?