service.go 888 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package proxy
  2. import (
  3. "go.uber.org/zap"
  4. "runtime/debug"
  5. "sync"
  6. )
  7. var (
  8. servicesMap = new(sync.Map)
  9. logger *zap.Logger
  10. )
  11. type Service struct {
  12. TCPConn TCP
  13. Name string
  14. }
  15. func (s *Service) Stop() {
  16. servicesMap.Delete(s.Name)
  17. s.TCPConn.Close()
  18. }
  19. func Run(name string, args TCPArgs, zapLogger *zap.Logger) *Service {
  20. logger = zapLogger
  21. service := &Service{
  22. TCPConn: &tcp{cfg: args},
  23. Name: name,
  24. }
  25. store, loaded := servicesMap.LoadOrStore(name, service)
  26. if loaded {
  27. service = store.(*Service)
  28. }
  29. go func() {
  30. defer func() {
  31. recoverErr := recover()
  32. if recoverErr != nil {
  33. logger.Sugar().Errorf("%s servcie crashed, ERR: %s\ntrace:%s", name, recoverErr, string(debug.Stack()))
  34. }
  35. }()
  36. startErr := service.TCPConn.Start()
  37. if startErr != nil {
  38. logger.Sugar().Errorf("%s servcie fail, ERR: %s", name, startErr)
  39. }
  40. }()
  41. return service
  42. }