diff --git a/diamond.go b/diamond.go index 9523c86..ccfdfdc 100644 --- a/diamond.go +++ b/diamond.go @@ -1,6 +1,7 @@ package aliacm import ( + "math/rand" "time" "github.com/sirupsen/logrus" @@ -63,6 +64,7 @@ type Diamond struct { c *cast.Cast units []Unit errHook Hook + r *rand.Rand } // New 产生Diamond实例 @@ -85,9 +87,14 @@ func New(addr, tenant, accessKey, secretKey string) (*Diamond, error) { if err != nil { return nil, err } + + s := rand.NewSource(time.Now().UnixNano()) + r := rand.New(s) + d := &Diamond{ option: option, c: c, + r: r, } return d, nil } diff --git a/query_ip.go b/query_ip.go index 9b26431..21714e9 100644 --- a/query_ip.go +++ b/query_ip.go @@ -18,7 +18,10 @@ func (d *Diamond) QueryIP() (string, error) { if !response.Success() { return "", errors.New(response.String()) } - ips := strings.Split(response.String(), "\n") - // TODO: randomly select one from ip list? - return ips[0], nil + ips := strings.Split(strings.TrimSpace(response.String()), "\n") + if len(ips) > 0 { + idx := d.r.Intn(len(ips)) + return ips[idx], nil + } + return "", nil } diff --git a/time.go b/time.go index dbf6920..5ce637d 100644 --- a/time.go +++ b/time.go @@ -1,6 +1,8 @@ package aliacm -import "time" +import ( + "time" +) const ( apiTimeout = 3 * time.Second