SHARE
TWEET

Untitled

a guest Jul 23rd, 2019 67 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "context"
  5.     "fmt"
  6.     "net/http"
  7.     "os"
  8.     "os/signal"
  9.     "syscall"
  10.     "time"
  11. )
  12.  
  13. var (
  14.     simpleHTTPServer      http.Server
  15.     sigChan               chan os.Signal
  16.     simpleServiceShutdown chan bool
  17. )
  18.  
  19. func simpleServiceStarter() {
  20.     mux := http.NewServeMux()
  21.     simpleHTTPServer := &http.Server{
  22.         Addr:           ":9000",
  23.         Handler:        mux,
  24.         ReadTimeout:    10 * time.Second,
  25.         WriteTimeout:   10 * time.Second,
  26.         MaxHeaderBytes: 1 << 20,
  27.     }
  28.     fmt.Printf("nstarting http server on :9000 ")
  29.     err := simpleHTTPServer.ListenAndServe()
  30.     if err != http.ErrServerClosed {
  31.         fmt.Printf("error starting simple service or closing listener - %vn", err)
  32.     }
  33.     fmt.Printf("simple service http server shutdown completed - %vn", err)
  34.  
  35.     // communicate with main thread
  36.     simpleServiceShutdown <- true
  37. }
  38.  
  39. func signalHandler() {
  40.     // Handle SIGINT and SIGHUP.
  41.     signal.Notify(sigChan, syscall.SIGINT, syscall.SIGHUP)
  42.  
  43.     sig := <-sigChan
  44.     fmt.Printf("nsignalHandler() received signal: %vn", sig)
  45.  
  46.     // gracefully shutdown http server
  47.     err := simpleHTTPServer.Shutdown(context.Background())
  48.     fmt.Printf("simple service shutdown on signal %v, error: %vn", sig, err)
  49.     close(sigChan)
  50.  
  51. }
  52.  
  53. func main() {
  54.     // block all async signals to this server. And we register only SIGINT and SIGHUP for now.
  55.     signal.Ignore()
  56.  
  57.     sigChan = make(chan os.Signal, 1)
  58.     simpleServiceShutdown = make(chan bool)
  59.     go signalHandler()
  60.  
  61.     go simpleServiceStarter()
  62.     <-simpleServiceShutdown // wait server to shutdown
  63.     close(simpleServiceShutdown)
  64. }
  65.      
  66. Run the program as:
  67. $ ./simpleHttp
  68.  
  69. starting http server on :9000
  70. signalHandler() received signal: interrupt
  71. simple service shutdown on signal interrupt, error: <nil>
  72. $
  73.  
  74. From another terminal send the signal as:
  75. tester 30202  4379  0 09:14 pts/8    00:00:00 ./simpleHttp
  76. kill -s SIGINT 30202
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top