rpcpubserver.go 1.2 KB

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