Guest User

Untitled

a guest
Oct 16th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "context"
  5. "io"
  6. "log"
  7. "net"
  8. "os"
  9. "os/signal"
  10. "sync"
  11. "syscall"
  12. "time"
  13.  
  14. "github.com/cloudflare/tableflip"
  15.  
  16. )
  17.  
  18. func handleConnection(ctx context.Context, wg *sync.WaitGroup, c net.Conn) {
  19. defer wg.Done()
  20. select {
  21. case <-ctx.Done():
  22. return
  23. default:
  24. io.WriteString(c, "topsecret")
  25. }
  26. }
  27.  
  28. func handleDataStream(ctx context.Context, wg *sync.WaitGroup, upg *tableflip.Upgrader, addr string) {
  29. defer wg.Done()
  30. // i can handle parent listeners here if they was created with such arguments in parent process, or create new listener
  31. l, _ := upg.Fds.Listen("tcp", addr)
  32.  
  33. for {
  34. select {
  35. case <-ctx.Done():
  36. return
  37. default:
  38. l.(*net.TCPListener).SetDeadline(time.Now().Add(time.Second * 3))
  39. c, err := l.Accept() // now i want to store all accepted connections in order to pass them on to the child process in the future
  40. if err != nil {
  41. continue
  42. }
  43.  
  44. wg.Add(1)
  45. go handleConnection(ctx, wg, c)
  46. }
  47. }
  48. }
  49.  
  50. func main() {
  51. wg := &sync.WaitGroup{}
  52. ctx, cancel := context.WithCancel(context.Background())
  53.  
  54. upg, _ := tableflip.New(tableflip.Options{})
  55. defer upg.Stop()
  56.  
  57. listenOn := []string{":8080", ":8085", "8090"}
  58. for _, addr := range listenOn {
  59. wg.Add(1)
  60. go handleDataStream(ctx, wg, upg, addr)
  61. }
  62.  
  63. for _, c := range upg.InheritConnections() { // i want to continue processing all parent connections if they exist.
  64. wg.Add(1)
  65. go handleConnection(ctx, wg, c)
  66. }
  67.  
  68. go func() {
  69. sig := make(chan os.Signal, 1)
  70. signal.Notify(sig, syscall.SIGHUP)
  71.  
  72. <-sig
  73. cancel()
  74. wg.Wait()
  75. _ := upg.Upgrade()
  76. }()
  77.  
  78. _ = upg.Ready()
  79. <-upg.Exit()
  80. }
Add Comment
Please, Sign In to add comment