Skip to content

Instantly share code, notes, and snippets.

@esimov
Created February 25, 2016 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esimov/4c8a3f83cc80c5b1aa98 to your computer and use it in GitHub Desktop.
Save esimov/4c8a3f83cc80c5b1aa98 to your computer and use it in GitHub Desktop.
Simple Go program to download xkcd images to local disk
package main
import (
"fmt"
"net/http"
"encoding/json"
"strconv"
"os"
"log"
"io"
)
var ComicURL string = "http://xkcd.com/"
type Comic struct {
Year string `json:"year"`
SafeTitle string `json:"safe_title"`
Transcript string `json:"transcript"`
Image string `json:"img"`
}
func main() {
for i:=1; i < 50; i++ {
result, err := GetComic(ComicURL + strconv.Itoa(i) + "/info.0.json")
if err != nil {
fmt.Errorf("Error %v", err)
}
extension := result.Image[len(result.Image)-4 : ]
img, err := os.Create("./xkcd/" + result.SafeTitle + extension)
if err != nil {
log.Fatal(err)
}
resp, err := http.Get(result.Image)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
_, err = io.Copy(img,resp.Body)
if err != nil {
log.Fatal(err)
}
defer img.Close()
fmt.Printf("URL : %s\n", result.Image)
}
}
func GetComic(url string)(*Comic, error) {
resp, err := http.Get(url)
if err != nil {
defer resp.Body.Close()
return nil, err
}
if resp.StatusCode != http.StatusOK {
fmt.Println("ERROR")
defer resp.Body.Close()
fmt.Errorf("Error trying to access the provided URL: %s", resp.Status)
return nil, err
}
var comicBlock Comic
result := json.NewDecoder(resp.Body).Decode(&comicBlock)
if result != nil {
defer resp.Body.Close()
return nil, err
}
defer resp.Body.Close()
return &comicBlock, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment