github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/f/context_test.go (about) 1 package f_test 2 3 import ( 4 "context" 5 "github.com/angenalZZZ/gofunc/f" 6 "log" 7 "net/http" 8 "time" 9 ) 10 11 //func TestContextWrapSignal(t *testing.T) { 12 // ctx, cancel := f.ContextWrapSignal(context.Background(), syscall.SIGUSR1) 13 // defer cancel() 14 // 15 // select { 16 // case <-ctx.Done(): 17 // t.Fatal("context should not be done") 18 // case <-time.After(10 * time.Millisecond): 19 // } 20 // 21 // if err := syscall.Kill(syscall.Getpid(), syscall.SIGUSR1); err != nil { 22 // t.Fatal("failed to signal") 23 // } 24 // 25 // select { 26 // case <-ctx.Done(): 27 // // expected 28 // case <-time.After(10 * time.Millisecond): 29 // t.Fatal("context should have been done") 30 // } 31 //} 32 33 func ExampleContextOnInterrupt() { 34 ctx, cancel := f.ContextOnInterrupt() 35 defer cancel() 36 37 s := &http.Server{ 38 Addr: ":8080", 39 } 40 go func() { 41 if err := s.ListenAndServe(); err != nil { 42 log.Fatal(err) 43 } 44 }() 45 46 // Wait for CTRL+C 47 <-ctx.Done() 48 49 // Stop the server 50 shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second) 51 defer shutdownCancel() 52 if err := s.Shutdown(shutdownCtx); err != nil { 53 log.Fatal(err) 54 } 55 }