美文网首页
channel使用场景:futures / promises

channel使用场景:futures / promises

作者: bocsoft | 来源:发表于2018-12-10 16:14 被阅读0次

    golang 虽然没有直接提供 futrue / promise 模型的操作原语,但通过 goroutine 和 channel 可以实现类似的功能:

    
    package main
    
    import (
        "io/ioutil"
        "log"
        "net/http"
    )
    
    //http request promise
    func RequestFuture(url string) <-chan []byte {
        c := make(chan []byte, 1)
        go func() {
            var body []byte
            defer func() {
                c <- body
            }()
    
            resp, err := http.Get(url)
            if err != nil {
                return
            }
            defer resp.Body.Close()
    
            body, _ = ioutil.ReadAll(resp.Body)
        }()
    
        return c
    }
    
    func main() {
        future := RequestFuture("https://api.github.com/users/octocat/orgs")
        body := <-future
        log.Printf("reponse length: %d", len(body))
        log.Printf("response content: %s",string(body))
    
        /*
         输出内容:
    2018/12/10 16:14:24 reponse length: 2
    2018/12/10 16:14:24 response content: []
         */
    }
    
    
    
    

    相关文章

      网友评论

          本文标题:channel使用场景:futures / promises

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