rpcpubserver.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package internal
  2. import (
  3. "os"
  4. "strings"
  5. "github.com/tal-tech/go-zero/core/discov"
  6. "github.com/tal-tech/go-zero/core/netx"
  7. )
  8. const (
  9. allEths = "0.0.0.0"
  10. envPodIp = "POD_IP"
  11. )
  12. func NewRpcPubServer(etcdEndpoints []string, etcdKey, listenOn string, opts ...ServerOption) (Server, error) {
  13. registerEtcd := func() error {
  14. pubListenOn := figureOutListenOn(listenOn)
  15. pubClient := discov.NewPublisher(etcdEndpoints, etcdKey, pubListenOn)
  16. return pubClient.KeepAlive()
  17. }
  18. server := keepAliveServer{
  19. registerEtcd: registerEtcd,
  20. Server: NewRpcServer(listenOn, opts...),
  21. }
  22. return server, nil
  23. }
  24. type keepAliveServer struct {
  25. registerEtcd func() error
  26. Server
  27. }
  28. func (ags keepAliveServer) Start(fn RegisterFn) error {
  29. if err := ags.registerEtcd(); err != nil {
  30. return err
  31. }
  32. return ags.Server.Start(fn)
  33. }
  34. func figureOutListenOn(listenOn string) string {
  35. fields := strings.Split(listenOn, ":")
  36. if len(fields) == 0 {
  37. return listenOn
  38. }
  39. host := fields[0]
  40. if len(host) > 0 && host != allEths {
  41. return listenOn
  42. }
  43. ip := os.Getenv(envPodIp)
  44. if len(ip) == 0 {
  45. ip = netx.InternalIp()
  46. }
  47. if len(ip) == 0 {
  48. return listenOn
  49. }
  50. return strings.Join(append([]string{ip}, fields[1:]...), ":")
  51. }