25 lines
		
	
	
	
		
			480 B
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			25 lines
		
	
	
	
		
			480 B
		
	
	
	
		
			Go
		
	
	
	
	
	
package context
 | 
						|
 | 
						|
import (
 | 
						|
	"context"
 | 
						|
	"os"
 | 
						|
	"os/signal"
 | 
						|
	"syscall"
 | 
						|
)
 | 
						|
 | 
						|
func SelfCancelingContextFromBackground() (context.Context, context.CancelFunc) {
 | 
						|
	return SelfCancelingContext(context.Background())
 | 
						|
}
 | 
						|
 | 
						|
func SelfCancelingContext(ctx context.Context) (context.Context, context.CancelFunc) {
 | 
						|
	c, done := context.WithCancel(ctx)
 | 
						|
	ch := make(chan os.Signal, 1)
 | 
						|
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
 | 
						|
	go func() {
 | 
						|
		for range ch {
 | 
						|
			done()
 | 
						|
		}
 | 
						|
	}()
 | 
						|
 | 
						|
	return c, done
 | 
						|
}
 |