2022-07-13 15:07:01 -04:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/tls"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type post struct {
|
|
|
|
Title string
|
|
|
|
Link string
|
|
|
|
}
|
|
|
|
|
2022-07-17 18:15:29 -04:00
|
|
|
func getNewestPost(subreddit string) (post, error) {
|
2022-07-13 15:07:01 -04:00
|
|
|
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 {
|
|
|
|
time.Sleep(5 * time.Second)
|
|
|
|
res, err = http.Get(url)
|
|
|
|
if err != nil {
|
2022-07-17 18:15:29 -04:00
|
|
|
return post{}, err
|
2022-07-13 15:07:01 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
body, readErr := ioutil.ReadAll(res.Body)
|
|
|
|
if readErr != nil {
|
2022-07-17 18:15:29 -04:00
|
|
|
return post{}, err
|
2022-07-13 15:07:01 -04:00
|
|
|
}
|
|
|
|
err = json.Unmarshal(body, &resp)
|
|
|
|
if err != nil {
|
2022-07-17 18:15:29 -04:00
|
|
|
return post{}, err
|
2022-07-13 15:07:01 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
return post{
|
|
|
|
Title: resp.Data.Children[0].Data.Title,
|
|
|
|
Link: resp.Data.Children[0].Data.URL,
|
2022-07-17 18:15:29 -04:00
|
|
|
}, nil
|
2022-07-13 15:07:01 -04:00
|
|
|
}
|