[Go] Download an image from a URL and save it to a file

Created on November 30, 2026

You can send an HTTP GET request with net/http and save the returned image bytes locally. Replace the example URL with the URL of an image you can access.

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

func main() {
    client := &http.Client{Timeout: 30 * time.Second}
    req, err := http.NewRequest(http.MethodGet, "https://example.com/dummy.png", nil)
    if err != nil {
        panic(err)
    }
    response, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer response.Body.Close()
    if response.StatusCode != http.StatusOK {
        panic(fmt.Errorf("download failed: %s", response.Status))
    }

    body, err := io.ReadAll(response.Body)
    if err != nil {
        panic(err)
    }
    if err := os.WriteFile("image.png", body, 0644); err != nil {
        panic(err)
    }
}

The program writes the response bytes to image.png, replacing an existing file with that name.

Go