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" }