save-xkcd.go (642B)
1 package xkcd 2 3 import ( 4 "fmt" 5 "io" 6 "log" 7 "os" 8 ) 9 10 // Save xkcd numbered num in /tmp 11 func SaveXKCD(num int) (msg string) { 12 api := detectAPI(num) 13 data := xkcdAPI(api) 14 num = data.Num 15 ext := getExt(data.Img) 16 img := getImg(data.Img, data.Link, ext) 17 img_resp := httpGet(img) 18 img_body := img_resp.Body 19 defer img_body.Close() 20 filename := fmt.Sprintf("/tmp/xkcd-%d.%s", num, ext) 21 file, err := os.Create(filename) 22 if err != nil { 23 log.Fatalf("Unable to save file. See %v.\n", err) 24 } 25 defer file.Close() 26 if _, err := io.Copy(file, img_body); err != nil { 27 log.Fatal(err) 28 } 29 msg = fmt.Sprintf("Saved %d to /tmp.\n", num) 30 return msg 31 }