Go从三个站点中返回响应最快的

利用协程可以轻松实现

package main

import (
    "fmt"
    "github.com/imroc/req"
)

func mirroredQuery() string {
    responses := make(chan string, 3)
    go func() { responses <- request("http://www.baidu.com") }()
    go func() { responses <- request("http://www.google.com") }()
    go func() { responses <- request("http://www.qq.com") }()

    return <-responses
}

//发送http请求方法
func request(hostname string) (response string) {
    r := req.New()
    r.Get(hostname)
    return hostname
}

func main() {
    fmt.Println(mirroredQuery())
}

  

原文地址:https://www.cnblogs.com/chenqionghe/p/8267267.html