Very new to Go (first simple project I\'m working on).
Question: How do I get an image from URL and then save it to my computer?
Here\'s what I have so far:<
There is no need to decode the file. Simply copy the response body to a file you've opened. Here's the deal in the modified example:
response.Body
is a stream of data, and implements the Reader
interface - meaning you can sequentially call Read
on it, as if it was an open file. Writer
interface. This is the opposite - it's a stream you can call Write
on.io.Copy
"patches" a reader and a writer, consumes the reader stream and writes its contents to a Writer. This is one of my favorite things about go - implicit interfaces. You don't have to declare you're implementing an interface, you just have to implement it to be used in some context. This allows mixing and matching of code that doesn't need to know about other code it's interacting with.
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
)
func main() {
url := "http://i.imgur.com/m1UIjW1.jpg"
// don't worry about errors
response, e := http.Get(url)
if e != nil {
log.Fatal(e)
}
defer response.Body.Close()
//open a file for writing
file, err := os.Create("/tmp/asdf.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Use io.Copy to just dump the response body to the file. This supports huge files
_, err = io.Copy(file, response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("Success!")
}
package main
import (
"io"
"net/http"
"os"
"fmt"
)
func main() {
img, _ := os.Create("image.jpg")
defer img.Close()
resp, _ := http.Get("http://i.imgur.com/Dz2r9lk.jpg")
defer resp.Body.Close()
b, _ := io.Copy(img, resp.Body)
fmt.Println("File size: ", b)
}
What is the type of response.Body
? You should just convert that into a []byte
if it is not and write that to disk. There is no reason to use the image
class unless you have some reason to treat the data as an image. Just treat the data as a series of bytes and write it to the disk.