69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"regexp"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
type post struct {
|
|
Title string
|
|
Link string
|
|
Number int
|
|
}
|
|
|
|
func getNewestPost(subreddit string) (post, error) {
|
|
var resp redditResp
|
|
re := regexp.MustCompile("([0-9]+)")
|
|
//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 {
|
|
return post{}, err
|
|
}
|
|
}
|
|
defer res.Body.Close()
|
|
body, readErr := ioutil.ReadAll(res.Body)
|
|
if readErr != nil {
|
|
return post{}, err
|
|
}
|
|
err = json.Unmarshal(body, &resp)
|
|
if err != nil {
|
|
return post{}, err
|
|
}
|
|
if len(resp.Data.Children) < 1 {
|
|
return post{}, errors.New("bad data from reddit")
|
|
}
|
|
reSearch := re.FindStringSubmatch(resp.Data.Children[0].Data.Title)
|
|
if len(reSearch) == 0 {
|
|
return post{}, fmt.Errorf("Something strange in data from reddit")
|
|
}
|
|
numS := reSearch[0]
|
|
num, err := strconv.Atoi(numS)
|
|
if err != nil || numS == "" {
|
|
num = -1
|
|
}
|
|
return post{
|
|
Title: resp.Data.Children[0].Data.Title,
|
|
Link: resp.Data.Children[0].Data.URL,
|
|
Number: num,
|
|
}, nil
|
|
}
|