forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcpubserver.go
76 lines (64 loc) · 1.64 KB
/
rpcpubserver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package internal
import (
"os"
"strings"
"github.com/zeromicro/go-zero/core/discov"
"github.com/zeromicro/go-zero/core/netx"
)
const (
allEths = "0.0.0.0"
envPodIp = "POD_IP"
)
// NewRpcPubServer returns a Server.
func NewRpcPubServer(etcd discov.EtcdConf, listenOn string, middlewares ServerMiddlewaresConf,
opts ...ServerOption) (Server, error) {
registerEtcd := func() error {
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))
}
if etcd.HasID() {
pubOpts = append(pubOpts, discov.WithId(etcd.ID))
}
pubClient := discov.NewPublisher(etcd.Hosts, etcd.Key, pubListenOn, pubOpts...)
return pubClient.KeepAlive()
}
server := keepAliveServer{
registerEtcd: registerEtcd,
Server: NewRpcServer(listenOn, middlewares, opts...),
}
return server, nil
}
type keepAliveServer struct {
registerEtcd func() error
Server
}
func (s keepAliveServer) Start(fn RegisterFn) error {
if err := s.registerEtcd(); err != nil {
return err
}
return s.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:]...), ":")
}