things-go / go-socks5

socks5 server in pure Golang with much custom optional. Full TCP/UDP and IPv4/IPv6 support.
MIT License
393 stars 68 forks source link

[FEATURE REQUEST] Add method `*Server.Shutdown` #7

Open zyxkad opened 2 years ago

zyxkad commented 2 years ago

Then we can shutdown it gracefully

sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)

select {
case <-sigs:
    timeoutCtx, cancel := context.WithTimeout(context.Background(), 16 * time.Second)
    defer cancel()
    // do some thing
    server.Shutdown(timeoutCtx)
}
Dorbmon commented 1 year ago

Yes, I need this shutdown function too.

the-hotmann commented 9 months ago

This actually would be very handy. Love the approach and would like to see it beeing implemented.

soluchok commented 8 months ago

You do not need a shutdown function to close the server. You can use the following code to achieve graceful shutdown.

// Create your own listener
l, err := net.Listen("tcp", ":7777")
if err != nil {
  // handle err
}

// Start a goroutine to listen to a context and close your listener when context is done
go func() {
  select {
  case <-ctx.Done():
    l.Close()
  }
}()

if err := server.Serve(l); err != nil {
  // handle err
}
zyxkad commented 8 months ago
  1. The shutdown method's context is created & passed when calling it, not before serve it
  2. Shutdown method should detect if there are active connection, if not, it should close immediately, else it will wait until the context is done