golang access http request to download resources

Under normal circumstances, the following piece of code can be obtained 响应结构体的字节流, and the response structure can be obtained by deserializing it. When the url is an Internet object resource, that is, when the url is accessed to download resources, the following piece of code is obtained.被资源的二进制流

func HttpGet(url string) ([]byte, error) {
	resp, err := http.Get(url)
	if err != nil {
		return nil, err
	}
	if resp == nil {
		return nil, fmt.Errorf("resp is nil")
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("resp status is %s", resp.Status)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}

After obtaining the byte stream of the file, it can be saved as a local file, or other actions can be performed, such as passing the binary stream to other places. The following is the implementation of saving the binary stream as a local file

row, err := HttpGet(url)

reader := bufio.NewReaderSize(raw, 1024*32);

file, err := os.Create(filename)
if err != nil {
 panic(err)
}
writer := bufio.NewWriter(file)

Reference : How Golang uses http Client to download files_Golang

Guess you like

Origin blog.csdn.net/qq_41767116/article/details/131161192