1. 程式人生 > >Go從三個站點中返回響應最快的

Go從三個站點中返回響應最快的

ror func .get hostname http res roc esp aid

利用協程可以輕松實現

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

  

Go從三個站點中返回響應最快的