美文网首页
Golang 错误的error处理方式

Golang 错误的error处理方式

作者: FredricZhu | 来源:发表于2019-06-14 21:18 被阅读0次
package main

import (
    "fmt"
    "net/http"
)

func main() {
    checkStatus := func(done <-chan interface{},
        urls ...string) <-chan *http.Response {
        responses := make(chan *http.Response)
        go func() {
            defer close(responses)
            for _, url := range urls {
                resp, err := http.Get(url)
                if err != nil {
                    fmt.Println(err)
                    continue
                }
                select {
                case <-done:
                    return
                case responses <- resp:
                }
            }
        }()
        return responses
    }

    done := make(chan interface{})
    defer close(done)
    urls := []string{"https://www.baidu.com", "https://badhost"}
    for response := range checkStatus(done, urls...) {
        fmt.Printf("Response %v\n", response.Status)
    }
}

程序输出如下,


image.png

相关文章

网友评论

      本文标题:Golang 错误的error处理方式

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