rpcpubserver.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // NewRpcPubServer returns a Server.
  13. func NewRpcPubServer(etcd discov.EtcdConf, listenOn string, opts ...ServerOption) (Server, error) {
  14. registerEtcd := func() error {
  15. pubListenOn := figureOutListenOn(listenOn)
  16. var pubOpts []discov.PubOption
  17. if etcd.HasAccount() {
  18. pubOpts = append(pubOpts, discov.WithPubEtcdAccount(etcd.User, etcd.Pass))
  19. }
  20. if etcd.HasTLS() {
  21. pubOpts = append(pubOpts, discov.WithPubEtcdTLS(etcd.CertFile, etcd.CertKeyFile,
  22. etcd.CACertFile, etcd.InsecureSkipVerify))
  23. }
  24. pubClient := discov.NewPublisher(etcd.Hosts, etcd.Key, pubListenOn, pubOpts...)
  25. return pubClient.KeepAlive()
  26. }
  27. server := keepAliveServer{
  28. registerEtcd: registerEtcd,
  29. Server: NewRpcServer(listenOn, opts...),
  30. }
  31. return server, nil
  32. }
  33. type keepAliveServer struct {
  34. registerEtcd func() error
  35. Server
  36. }
  37. func (ags keepAliveServer) Start(fn RegisterFn) error {
  38. if err := ags.registerEtcd(); err != nil {
  39. return err
  40. }
  41. return ags.Server.Start(fn)
  42. }
  43. func figureOutListenOn(listenOn string) string {
  44. fields := strings.Split(listenOn, ":")
  45. if len(fields) == 0 {
  46. return listenOn
  47. }
  48. host := fields[0]
  49. if len(host) > 0 && host != allEths {
  50. return listenOn
  51. }
  52. ip := os.Getenv(envPodIp)
  53. if len(ip) == 0 {
  54. ip = netx.InternalIp()
  55. }
  56. if len(ip) == 0 {
  57. return listenOn
  58. }
  59. return strings.Join(append([]string{ip}, fields[1:]...), ":")
  60. }