In this section, we are going to see how to download files from the internet. For this, we are going to take an example of downloading an image. We are going to type the URL of the image, which the logo of Go. Check the following code:
package main import ( "net/http" "os" "io" "fmt" ) func main(){ imageUrl := "https://golang.org/doc/gopher/doc.png" response, err := http.Get(imageUrl) if err != nil{ panic(err) } defer response.Body.Close() file, err2 := os.Create("gopher.png") if err2 != nil{ panic(err2) } _, err3 := io.Copy(file, response.Body) if err3 != nil{ panic(err3) } file.Close() fmt.Println("Image downloading is successful.") }
As you can see, we've used the http.Get()
method here. If our err
is not nil
, we've typed panic(err)
and we are going to exit the defer response.Body.Close()
function. Before our function exits, we're going to close the body of the out
response. So, the first thing we have to...