Skip to content

Instantly share code, notes, and snippets.

@skwair
Created May 1, 2018 12:04
Show Gist options
  • Save skwair/c67d328e1040f638a07bf841be94fd11 to your computer and use it in GitHub Desktop.
Save skwair/c67d328e1040f638a07bf841be94fd11 to your computer and use it in GitHub Desktop.
gRPC Graceful stop with context.
// shutdown adds a context.Context to the GracefulStop method of
// grpc.Server, allowing to set a timeout before calling Stop.
func shutdown(ctx context.Context, s *grpc.Server) error {
ok := make(chan struct{})
// NOTE: GracefulStop will return instantly
// when Stop it called, preventing this
// goroutine from leaking.
go func() {
s.GracefulStop()
close(ok)
}()
select {
case <-ok:
return nil
case <-ctx.Done():
s.Stop()
return ctx.Err()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment