Skip to content

Instantly share code, notes, and snippets.

@esimov

esimov/xkcd.go

Created Feb 25, 2016
Embed
What would you like to do?
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