golang using timeouts with channels

后端 未结 4 1484
抹茶落季
抹茶落季 2020-12-30 03:32

I am using goroutines/channels to check if list of urls are reachable. Here is my code. This seems to always return true. Why is the timeout case not getting executed? The g

4条回答
  •  鱼传尺愫
    2020-12-30 03:41

    The reason this always returns true is you are calling check(u) within your select statement. You need to call it within a go routine and then use a select to either wait for the result or timeout.

    In case you want to check the reachability of multiple URLs in parallel you need to restructure your code.

    First create a function which checks the reachability of one URL:

    func IsReachable(url string) bool {
        ch := make(chan bool, 1)
        go func() { ch <- check(url) }()
        select {
        case reachable := <-ch:
            return reachable
        case <-time.After(time.Second):
            // call timed out
            return false
        }
    }
    

    Then call this function from a loop:

    urls := []string{"url1", "url2", "url3"}
    for _, url := range urls {
        go func() { fmt.Println(IsReachable(url)) }()
    }
    

    Play

提交回复
热议问题