service.go 781 B

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