2021-06-30 17:15:28 +00:00
|
|
|
// Copyright 2017 Drone.IO Inc.
|
|
|
|
//
|
|
|
|
// This file is licensed under the terms of the MIT license.
|
|
|
|
// For a copy, see https://opensource.org/licenses/MIT.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2021-11-24 01:01:12 +00:00
|
|
|
// WithContextFunc returns a copy of parent context that is canceled when
|
2021-06-30 17:15:28 +00:00
|
|
|
// an os interrupt signal is received. The callback function f is invoked
|
|
|
|
// before cancellation.
|
|
|
|
func WithContextFunc(ctx context.Context, f func()) context.Context {
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
go func() {
|
2021-10-09 01:14:25 +00:00
|
|
|
c := make(chan os.Signal, 1)
|
2021-06-30 17:15:28 +00:00
|
|
|
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
defer signal.Stop(c)
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
case <-c:
|
|
|
|
f()
|
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return ctx
|
|
|
|
}
|