channel使用场景:futures / promises

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)