Last active
June 2, 2018 04:26
-
-
Save byronvanstien/35881c4e1bd05b46e4337f13d92ee9de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"flag" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
) | |
// Marshalling | |
type XKCD struct { | |
Month string | |
Num int | |
Link string | |
Year string | |
News string | |
SafeTitle string `json:"safe_title"` | |
Transcript string | |
Alt string | |
Img string | |
Title string | |
Day string | |
} | |
func main() { | |
// Flags | |
xkcdURL := flag.String("xkcd", "https://xkcd.com/info.0.json", "Link to XKCD data that you want") | |
downloadImage := flag.Bool("download", false, "True if you want to download the image else False") | |
flag.Parse() | |
// Request Endpoint | |
resp, err := http.Get(*xkcdURL) | |
// Log if it dies | |
if err != nil { | |
log.Fatal(err) | |
} | |
// No idea | |
defer resp.Body.Close() | |
// Get the JSON data | |
respBody, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
log.Fatal(err) | |
} | |
xkcd := XKCD{} | |
// Map JSON to the struct | |
json.Unmarshal(respBody, &xkcd) | |
// If the user wants to download the image | |
if *downloadImage { | |
// Request the actual image | |
resp, err := http.Get(xkcd.Img) | |
if err != nil { | |
log.Fatal(err) | |
} else { | |
// Create file to store image | |
file, err := os.Create("./download.png") | |
defer file.Close() | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Write image data | |
_, err = io.Copy(file, resp.Body) | |
fmt.Println("Downloaded file") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment