go-zero/zrpc/internal/rpcpubserver.go

77 lines
1.6 KiB
Go
Raw Normal View History

2020-07-29 18:06:57 +08:00
package internal
2020-07-26 17:09:05 +08:00
2021-02-17 21:42:22 +08:00
import (
"os"
"strings"
"github.com/zeromicro/go-zero/core/discov"
"github.com/zeromicro/go-zero/core/netx"
2021-02-17 21:42:22 +08:00
)
const (
allEths = "0.0.0.0"
envPodIp = "POD_IP"
)
2020-07-26 17:09:05 +08:00
2021-03-01 23:52:44 +08:00
// NewRpcPubServer returns a Server.
func NewRpcPubServer(etcd discov.EtcdConf, listenOn string, middlewares ServerMiddlewaresConf,
opts ...ServerOption) (Server, error) {
2020-07-26 17:09:05 +08:00
registerEtcd := func() error {
2021-02-17 21:42:22 +08:00
pubListenOn := figureOutListenOn(listenOn)
var pubOpts []discov.PubOption
if etcd.HasAccount() {
pubOpts = append(pubOpts, discov.WithPubEtcdAccount(etcd.User, etcd.Pass))
}
if etcd.HasTLS() {
pubOpts = append(pubOpts, discov.WithPubEtcdTLS(etcd.CertFile, etcd.CertKeyFile,
etcd.CACertFile, etcd.InsecureSkipVerify))
}
2023-03-11 14:57:56 +08:00
if etcd.HasID() {
pubOpts = append(pubOpts, discov.WithId(etcd.ID))
}
pubClient := discov.NewPublisher(etcd.Hosts, etcd.Key, pubListenOn, pubOpts...)
2020-07-26 17:09:05 +08:00
return pubClient.KeepAlive()
}
server := keepAliveServer{
registerEtcd: registerEtcd,
Server: NewRpcServer(listenOn, middlewares, opts...),
2020-07-26 17:09:05 +08:00
}
return server, nil
}
type keepAliveServer struct {
registerEtcd func() error
Server
}
2022-07-22 23:16:38 +08:00
func (s keepAliveServer) Start(fn RegisterFn) error {
if err := s.registerEtcd(); err != nil {
2020-07-26 17:09:05 +08:00
return err
}
2022-07-22 23:16:38 +08:00
return s.Server.Start(fn)
2020-07-26 17:09:05 +08:00
}
2021-02-17 21:42:22 +08:00
func figureOutListenOn(listenOn string) string {
fields := strings.Split(listenOn, ":")
if len(fields) == 0 {
return listenOn
}
host := fields[0]
if len(host) > 0 && host != allEths {
return listenOn
}
ip := os.Getenv(envPodIp)
if len(ip) == 0 {
ip = netx.InternalIp()
}
if len(ip) == 0 {
return listenOn
}
return strings.Join(append([]string{ip}, fields[1:]...), ":")
}