Refactor error handling and improve code readability
All checks were successful
🚨 Test Code Base / 🔍 🐹 Go Tests (push) Successful in 1m3s
🚨 Test Code Base / 🧹 Lint (push) Successful in 1m20s

This commit is contained in:
2025-08-26 12:33:09 -04:00
parent 586c434e6a
commit 537427f4d4
6 changed files with 40 additions and 15 deletions

View File

@@ -60,15 +60,16 @@ func GetLatestImage(httpGet func(url string) (*http.Response, error)) (string, e
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(response.Body)
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)

View File

@@ -2,9 +2,6 @@ package reddit
import (
"context"
"github.com/labstack/echo/v4"
"github.com/siteworxpro/top-wallpaper/redis"
"github.com/siteworxpro/top-wallpaper/resize"
"io"
"net/http"
"net/url"
@@ -12,6 +9,10 @@ import (
"strconv"
"strings"
"time"
"github.com/labstack/echo/v4"
"github.com/siteworxpro/top-wallpaper/redis"
"github.com/siteworxpro/top-wallpaper/resize"
)
func Fetch(ctx context.Context) {
@@ -50,6 +51,11 @@ func Fetch(ctx context.Context) {
default:
val, err := rc.Get(redis.CacheKey)
if err != nil {
l.Error("Error fetching from Redis: ", err)
break
}
if val != "" {
l.Info("Reddit image fetched from cache...")
@@ -76,11 +82,11 @@ func Fetch(ctx context.Context) {
Timeout: 10 * time.Second,
}
response, err := httpClient.Do(request)
response, e := httpClient.Do(request)
if err != nil {
l.Error("Error fetching image from Reddit: ", err)
return nil, err
if e != nil {
l.Error("Error fetching image from Reddit: ", e)
return nil, e
}
if response.StatusCode != http.StatusOK {
@@ -94,6 +100,11 @@ func Fetch(ctx context.Context) {
return response, nil
})
if err != nil {
l.Error("Error getting latest image URL: ", err)
break
}
response, err := http.Get(latestImageVal)
if err != nil {
l.Error("Error fetching image from Reddit: ", err)
@@ -119,6 +130,11 @@ func Fetch(ctx context.Context) {
imageData := string(imageDataBytes)
resized, err := resize.Shrink(imageData, uint(size), 70)
if err != nil {
l.Error("Error resizing image: ", err)
break
}
err = rc.Set(redis.CacheKey, resized, 10*time.Minute)
if err != nil {
l.Warn("could not cache image")