Files
unitech-golib/qgrpc/config.go
2020-04-06 19:57:19 +08:00

67 lines
1.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package qgrpc
import (
"fmt"
"net"
"os"
"strings"
)
// 基础配置,公共字段
type BasicConfig struct {
DialTimeout int `toml:"dial_timeout"` // 连接超时时间
KeepAlive int `toml:"keep_alive"` // 保活时间
EndPoints []string `toml:"endpoints"` // etcd的地址
Prefix string `toml:"prefix"` // etcd服务的路径前缀区分环境用
}
// 服务端配置
type ServerConfig struct {
BasicConfig
Servers []string `toml:"servers"` // 注册的服务名称,可以是多个
Addr string `toml:"addr"` // 服务地址
}
func (self *ServerConfig) GetAddr() string {
if strings.HasPrefix(self.Addr, ":") {
localIP := getLocalIP()
return fmt.Sprintf("%s%s", localIP, self.Addr)
}
return self.Addr
}
// 客户端配置
type ClientConfig struct {
BasicConfig
WatchServers []string `toml:"watch_servers"` // 依赖的服务名称,多个服务用','分割;每个服务名后增加'|ip:port'表示默认连接的服务地址
}
func getHostName() string {
if h, err := os.Hostname(); err == nil {
return h
}
return getLocalIP()
}
//获取本机的内网Ip, 如果发现对方的ip 和自己的ip 相同用127.0.0.1 替代
func getLocalIP() string {
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
addrs, _ := i.Addrs()
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
ipAddr := ip.String()
if strings.HasPrefix(ipAddr, "172.") || strings.HasPrefix(ipAddr, "192.") || strings.HasPrefix(ipAddr, "10.") {
return ipAddr
}
}
}
return "127.0.0.1"
}