service.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package proxy
  2. import (
  3. "fmt"
  4. "go.uber.org/zap"
  5. "net"
  6. "runtime/debug"
  7. "sync"
  8. )
  9. var (
  10. servicesMap = new(sync.Map)
  11. logger *zap.Logger
  12. )
  13. type Service struct {
  14. TCPConn TCP
  15. Name string
  16. }
  17. func (s *Service) Stop() {
  18. servicesMap.Delete(s.Name)
  19. s.TCPConn.Close()
  20. }
  21. func Run(name string, args TCPArgs, zapLogger *zap.Logger) *Service {
  22. logger = zapLogger
  23. service := &Service{
  24. TCPConn: &tcp{cfg: args},
  25. Name: name,
  26. }
  27. store, loaded := servicesMap.LoadOrStore(name, service)
  28. if loaded {
  29. service = store.(*Service)
  30. }
  31. go func() {
  32. defer func() {
  33. recoverErr := recover()
  34. if recoverErr != nil {
  35. logger.Sugar().Errorf("%s servcie crashed, ERR: %s\ntrace:%s", name, recoverErr, string(debug.Stack()))
  36. }
  37. }()
  38. startErr := service.TCPConn.Start()
  39. if startErr != nil {
  40. logger.Sugar().Errorf("%s servcie fail, ERR: %s", name, startErr)
  41. }
  42. }()
  43. return service
  44. }
  45. ///////////////////////////////////////////////////////////////////////////
  46. type Listener struct {
  47. ip string
  48. port int
  49. Listener net.Listener
  50. errAcceptHandler func(err error)
  51. }
  52. func NewListener(ip string, port int) Listener {
  53. return Listener{
  54. ip: ip,
  55. port: port,
  56. errAcceptHandler: func(err error) {
  57. logger.Sugar().Errorf("accept error , ERR:%s", err)
  58. },
  59. }
  60. }
  61. func (sc *Listener) ListenTCP(fn func(conn net.Conn)) (err error) {
  62. sc.Listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", sc.ip, sc.port))
  63. if err == nil {
  64. go func() {
  65. defer func() {
  66. if e := recover(); e != nil {
  67. logger.Sugar().Infof("ListenTCP crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
  68. }
  69. }()
  70. for {
  71. var conn net.Conn
  72. conn, err = sc.Listener.Accept()
  73. if err == nil {
  74. go func() {
  75. defer func() {
  76. if e := recover(); e != nil {
  77. logger.Sugar().Infof("connection handler crashed , err : %s , \ntrace:%s", e, string(debug.Stack()))
  78. }
  79. }()
  80. fn(conn)
  81. }()
  82. } else {
  83. sc.errAcceptHandler(err)
  84. break
  85. }
  86. }
  87. }()
  88. }
  89. return
  90. }
  91. func (sc *Listener) CloseListen() error {
  92. return sc.Listener.Close()
  93. }