package main import ( "crypto/tls" "encoding/json" "fmt" "io/ioutil" "log" "net/http" "time" ) type post struct { Title string Link string } func getNewestPost(subreddit string) post { var resp redditResp //building request from scratch because reddit api is weird url := fmt.Sprintf("https://www.reddit.com/r/%v/new.json?sort=new&limit=1", subreddit) req, _ := http.NewRequest("GET", url, nil) req.Header.Set("User-Agent", "Custom Agent") req.Header.Set("Host", "reddit.com") var defaultClient = http.Client{ Transport: &http.Transport{ TLSNextProto: map[string]func(authority string, c *tls.Conn) http.RoundTripper{}, }, } res, err := defaultClient.Do(req) if err != nil { log.Printf("Got %v, retrying in 5s", err) time.Sleep(5 * time.Second) res, err = http.Get(url) if err != nil { log.Printf("Got %v, not trying again", err) return post{} } } defer res.Body.Close() body, readErr := ioutil.ReadAll(res.Body) if readErr != nil { log.Fatalf("error reading reddit resp: %v", readErr) } err = json.Unmarshal(body, &resp) if err != nil { log.Fatalf("unmarshal error: %v", err) } return post{ Title: resp.Data.Children[0].Data.Title, Link: resp.Data.Children[0].Data.URL, } }