Push poorly written test can down the road another ten years

This commit is contained in:
2025-04-21 22:42:38 -04:00
parent c49e6d6c54
commit c00032c7c4
4 changed files with 240 additions and 213 deletions

88
reddit/client.go Normal file
View File

@@ -0,0 +1,88 @@
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() (string, error) {
response, err := http.Get("https://www.reddit.com/r/wallpaper/.json")
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(response.Body)
if response.StatusCode != http.StatusOK {
return "", fmt.Errorf("error fetching reddit data: %s", response.Status)
}
jsonBytes, err := io.ReadAll(response.Body)
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
}