美文网首页
Golang控制大于3个Error之后退出打印

Golang控制大于3个Error之后退出打印

作者: FredricZhu | 来源:发表于2019-06-14 21:51 被阅读0次
    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    type Result struct {
        Error    error
        Response *http.Response
    }
    
    func main() {
        checkStatus := func(done <-chan interface{},
            urls ...string) <-chan Result {
            results := make(chan Result)
            go func() {
                defer close(results)
                for _, url := range urls {
                    resp, err := http.Get(url)
                    result := Result{
                        Error:    err,
                        Response: resp,
                    }
    
                    select {
                    case <-done:
                        return
                    case results <- result:
                    }
                }
            }()
            return results
        }
    
        done := make(chan interface{})
        defer close(done)
        errorCount := 0
        urls := []string{"a", "https://www.baidu.com", "b", "c", "d", "https://badhosts"}
        for result := range checkStatus(done, urls...) {
            if result.Error != nil {
                fmt.Printf("Error: %v \n", result.Error)
                errorCount += 1
                if errorCount >= 3 {
                    fmt.Println("Too many errors ,break")
                    break
                }
                continue
            }
            fmt.Printf("Response: %v \n", result.Response.Status)
        }
    }
    

    程序输出如下,


    image.png

    相关文章

      网友评论

          本文标题:Golang控制大于3个Error之后退出打印

          本文链接:https://www.haomeiwen.com/subject/ompmfctx.html