package consul import ( "fmt" "github.com/hashicorp/consul/api" "math/rand" "strconv" ) func GetAgentInfo(client *api.Client) (string, string) { info, err := client.Agent().Self() if err != nil { fmt.Printf("%v\n", err) return "", "" } if info == nil { fmt.Println("Fail to get consul info.") return "", "" } ip := "" inter := info["DebugConfig"]["AdvertiseAddrLAN"] switch inter.(type) { case string: ip = inter.(string) break } nodeName := "" inter = info["Config"]["NodeName"] switch inter.(type) { case string: nodeName = inter.(string) break } return ip, nodeName } func SelectService(cataLog *api.Catalog, serviceName string, nodeName string) (string, error) { services, _, err := cataLog.Service(serviceName, "", nil) if err != nil { return "", err } if len(services) == 0 { fmt.Println("userCenter not found in catalog.") return "", nil } var count int32 = 0 addr := "" for _, s := range services { fmt.Printf("service info: %v\n", s) if s.ServiceWeights.Passing == 1 { count++ if s.Node == nodeName { addr = s.ServiceAddress + ":" + strconv.Itoa(s.ServicePort) break } else { if rand.Int31n(count) == 0 { addr = s.ServiceAddress + ":" + strconv.Itoa(s.ServicePort) } } } } return addr, nil } func GetServices(cataLog *api.Catalog, serviceName string) ([]string, error) { addrs := make([]string, 0) services, _, err := cataLog.Service(serviceName, "", nil) if err == nil { for _, s := range services { fmt.Printf("service info: %s, %s, %s:%d", s.ID, s.Node, s.ServiceAddress, s.ServicePort) if s.ServiceWeights.Passing == 1 { addrs = append(addrs, s.ServiceAddress+":"+strconv.Itoa(s.ServicePort)) } } } return addrs, nil }