xkcd-go

Golang tool to read latest, random, or a specific xkcd comic (and download it too).
git clone http://git.hanabi.in/repos/xkcd-go.git
Log | Files | Refs | README | LICENSE

fns.go (1312B)


      1 package xkcd
      2 
      3 import (
      4 	"encoding/json"
      5 	"io/ioutil"
      6 	"log"
      7 	"math/rand"
      8 	"net/http"
      9 	"strings"
     10 	"time"
     11 )
     12 
     13 const (
     14 	explainxkcd = "https://www.explainxkcd.com/wiki/index.php/"
     15 )
     16 
     17 func getImg(img, link, ext string) (res string) {
     18 	res = img
     19 	if strings.HasPrefix(link, "https://xkcd.com/") {
     20 		full_ext := "." + ext
     21 		first_part := strings.Replace(img, full_ext, "", -1)
     22 		res = first_part + "_large" + full_ext
     23 	}
     24 	return res
     25 }
     26 
     27 func getExt(str string) (ext string) {
     28 	arr := strings.Split(str, ".")
     29 	return arr[len(arr)-1]
     30 }
     31 
     32 func httpGet(url string) *http.Response {
     33 	client := &http.Client{}
     34 	resp, err := client.Get(url)
     35 	if err != nil {
     36 		log.Fatalf("Unable to access XKCD, see: %v.\n", err)
     37 	}
     38 	return resp
     39 }
     40 
     41 func xkcdAPI(api string) (data xkcdResp) {
     42 	resp := httpGet(api)
     43 	defer resp.Body.Close()
     44 	respIsJson := resp.Header.Get("Content-Type") == "application/json"
     45 	if !respIsJson {
     46 		log.Fatal("Unexpected response.")
     47 	}
     48 	body, err := ioutil.ReadAll(resp.Body)
     49 	if err != nil {
     50 		log.Fatalf("Unable to read the response, see %v.\n", err)
     51 	}
     52 	if err = json.Unmarshal(body, &data); err != nil {
     53 		log.Fatalf("Unable to parse the response, see %v.\n", err)
     54 	}
     55 	return data
     56 }
     57 
     58 func getRndXKCDIdx(max int) (rnd_idx int) {
     59 	rand.Seed(time.Now().UnixNano())
     60 	rnd_idx = rand.Intn(max+1) + 1
     61 	return rnd_idx
     62 }