Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #102 Load from HTTP GET request into a file

Make an HTTP request with method GET to the URL u, then store the body of the response in the file result.txt. Try to save the data as it arrives if possible, without having all its content in memory at once.

import "fmt"
import "io"
import "net/http"
out, err := os.Create("result.txt")
if err != nil {
	return err
}
defer out.Close()

resp, err := http.Get(u)
if err != nil {
	return err
}
defer func() {
	io.Copy(io.Discard, resp.Body)
	resp.Body.Close()
}()
if resp.StatusCode != 200 {
	return fmt.Errorf("Status: %v", resp.Status)
}

_, err = io.Copy(out, resp.Body)
if err != nil {
	return err
}

resp has type *http.Response.
It is idiomatic and strongly recommended to check errors at each step, except for the calls to Close.
import std.net.curl;
download(u, "result.txt");

New implementation...
< >
programming-idioms.org