channel实现future + promise类似的机制

package main

import (
	"io/ioutil"
	"log"
	"net/http"
)

func RequestFuture(url string) <-chan []byte {
	c := make(chan []byte, 1)

	go func() {
		var body []byte

		defer func() {
			c <- body
		}()

		res, err := http.Get(url)

		if err != nil {
			return
		}

		defer res.Body.Close()

		body, _ = ioutil.ReadAll(res.Body)
	}()

	return c
}

func main() {
	future := RequestFuture("https://gitee.com/jianan/projects")
	body := <-future
	log.Printf(string(body))
}

猜你喜欢

转载自blog.csdn.net/themagickeyjianan/article/details/106981577
今日推荐