go-zero/zrpc/internal/rpcpubserver.go
Kevin Wan 20f665ede8
implement k8s service discovery (#988)
* implement k8s service discovery

* simplify code

* use default namespace if not provided

* disable codecov bot comment

* ignore adhoc dir

* simplify building target in NewClient

* reformat code

* Fix filepath (#990)

* format code, and reorg imports (#991)

* add more unit test

Co-authored-by: anqiansong <anqiansong@gmail.com>
2021-09-04 10:27:08 +08:00

66 lines
1.2 KiB
Go

package internal
import (
"os"
"strings"
"github.com/tal-tech/go-zero/core/discov"
"github.com/tal-tech/go-zero/core/netx"
)
const (
allEths = "0.0.0.0"
envPodIp = "POD_IP"
)
// NewRpcPubServer returns a Server.
func NewRpcPubServer(etcdEndpoints []string, etcdKey, listenOn string,
opts ...ServerOption) (Server, error) {
registerEtcd := func() error {
pubListenOn := figureOutListenOn(listenOn)
pubClient := discov.NewPublisher(etcdEndpoints, etcdKey, pubListenOn)
return pubClient.KeepAlive()
}
server := keepAliveServer{
registerEtcd: registerEtcd,
Server: NewRpcServer(listenOn, opts...),
}
return server, nil
}
type keepAliveServer struct {
registerEtcd func() error
Server
}
func (ags keepAliveServer) Start(fn RegisterFn) error {
if err := ags.registerEtcd(); err != nil {
return err
}
return ags.Server.Start(fn)
}
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:]...), ":")
}