package api import ( "fmt" "net" "os" "path/filepath" "regexp" ) // getExeFilename func getExeFilename() string { _, logfilename := filepath.Split(os.Args[0]) if logfilename == "" { panic("get exe filename failed") } return logfilename } // preferencesMatch func preferencesMatch(s string, preferences ...string) bool { for _, pstr := range preferences { reg := regexp.MustCompile(pstr) if reg.Match([]byte(s)) { return true } } return false } // getInstanceIpAddress func getInstanceIpAddress(preferences ...string) string { addrs, err := net.InterfaceAddrs() if err != nil { panic(fmt.Sprintf("getInstanceIpAddress failed: [%s]", err)) } prefer := func() func(string) bool { if len(preferences) <= 0 { return nil } return func(ip string) bool { return preferencesMatch(ip, preferences...) } }() var ipnets = []*net.IPNet{} for _, address := range addrs { if ipnet, ok := address.(*net.IPNet); !ok { continue } else if ipnet.IP.IsLoopback() { continue } else if ipv4 := ipnet.IP.To4(); ipv4 == nil { continue } else if prefer == nil { var n = *ipnet ipnets = append(ipnets, &n) continue } else if prefer != nil && prefer(ipv4.String()) { return ipv4.String() } } // TODO: sort & return first if len(ipnets) > 0 { return ipnets[0].IP.To4().String() } panic(fmt.Sprintf("getInstanceIpAddreass failed,"+ "preferences=[%v], ipnets=[%v]", preferences, ipnets)) }