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

服务器

浏览数:91

2019-9-6

AD:资源代下载服务

利用协程可以轻松实现

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())
}

  

作者:雪山飞猪