
Reviewed-on: #1 Co-authored-by: Ron Rise <ron@siteworxpro.com> Co-committed-by: Ron Rise <ron@siteworxpro.com>
90 lines
2.1 KiB
Go
90 lines
2.1 KiB
Go
package reddit
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
type redditResponse struct {
|
|
Kind string `json:"kind"`
|
|
Data struct {
|
|
After string `json:"after"`
|
|
Dist int `json:"dist"`
|
|
ModHash string `json:"modhash"`
|
|
GeoFilter string `json:"geo_filter"`
|
|
Children []struct {
|
|
Kind string `json:"kind"`
|
|
Data struct {
|
|
ApprovedAtUtc interface{} `json:"approved_at_utc"`
|
|
Subreddit string `json:"subreddit"`
|
|
SelfText string `json:"selftext"`
|
|
Url string `json:"url"`
|
|
UrlOverriddenByDest string `json:"url_overridden_by_dest"`
|
|
MediaMetadata map[string]struct {
|
|
Status string `json:"status"`
|
|
Id string `json:"id"`
|
|
E string `json:"e"`
|
|
M string `json:"m"`
|
|
S struct {
|
|
U string `json:"u"`
|
|
X int `json:"x"`
|
|
Y int `json:"y"`
|
|
} `json:"s"`
|
|
P []struct {
|
|
U string `json:"u"`
|
|
X int `json:"x"`
|
|
Y int `json:"y"`
|
|
} `json:"p"`
|
|
} `json:"media_metadata"`
|
|
Preview struct {
|
|
Enabled bool `json:"enabled"`
|
|
Images []struct {
|
|
Source struct {
|
|
Url string `json:"url"`
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
} `json:"source"`
|
|
} `json:"images"`
|
|
} `json:"preview"`
|
|
} `json:"data"`
|
|
} `json:"children"`
|
|
} `json:"data"`
|
|
}
|
|
|
|
func GetLatestImage(httpGet func(url string) (*http.Response, error)) (string, error) {
|
|
|
|
response, err := httpGet("https://www.reddit.com/r/wallpaper/.json")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer response.Body.Close()
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
return "", fmt.Errorf("error fetching reddit data: %s", response.Status)
|
|
}
|
|
|
|
jsonBytes, err := io.ReadAll(response.Body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
redditData := redditResponse{}
|
|
err = json.Unmarshal(jsonBytes, &redditData)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
index := 1
|
|
url := redditData.Data.Children[index].Data.UrlOverriddenByDest
|
|
|
|
for strings.Contains(url, "gallery") {
|
|
index++
|
|
url = redditData.Data.Children[index].Data.UrlOverriddenByDest
|
|
}
|
|
|
|
return url, nil
|
|
}
|