You've already forked top-wallpaper
Push poorly written test can down the road another ten years
This commit is contained in:
90
http/handler.go
Normal file
90
http/handler.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/labstack/echo/v4"
|
||||
client "github.com/siteworxpro/top-wallpaper/reddit"
|
||||
"github.com/siteworxpro/top-wallpaper/resize"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Get(c echo.Context) error {
|
||||
cc := c.(*CustomContext)
|
||||
|
||||
var latestImageVal string
|
||||
var err error
|
||||
if cc.redis != nil {
|
||||
latestImage := cc.redis.Get(context.TODO(), "latestImage")
|
||||
latestImageVal, err = latestImage.Result()
|
||||
}
|
||||
|
||||
if err != nil || latestImageVal == "" {
|
||||
c.Logger().Info("Fetching latest image")
|
||||
latestImageVal, err = client.GetLatestImage()
|
||||
if err != nil {
|
||||
return c.String(http.StatusInternalServerError, "Error fetching latest image")
|
||||
}
|
||||
|
||||
if cc.redis != nil {
|
||||
cmd := cc.redis.Set(context.TODO(), "latestImage", latestImageVal, 600*time.Second)
|
||||
if cmd.Err() != nil {
|
||||
c.Logger().Warn("could not cache image")
|
||||
}
|
||||
}
|
||||
} else {
|
||||
c.Logger().Info("Image name fetched from cache")
|
||||
}
|
||||
|
||||
var imageData string
|
||||
if cc.redis != nil {
|
||||
latestImageBin := cc.redis.Get(context.TODO(), "latestImage:bin:"+latestImageVal)
|
||||
imageData = latestImageBin.Val()
|
||||
}
|
||||
|
||||
if imageData == "" {
|
||||
response, err := http.Get(latestImageVal)
|
||||
if err != nil {
|
||||
return c.String(http.StatusInternalServerError, "Error fetching image")
|
||||
}
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return c.String(http.StatusInternalServerError, "Error fetching image")
|
||||
}
|
||||
|
||||
defer func(Body io.ReadCloser) {
|
||||
_ = Body.Close()
|
||||
}(response.Body)
|
||||
|
||||
imageDataBytes, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return c.String(http.StatusInternalServerError, "Error fetching image")
|
||||
}
|
||||
|
||||
imageData = string(imageDataBytes)
|
||||
|
||||
imageData, err := resize.Shrink(imageData, 1200, 70)
|
||||
|
||||
if err != nil {
|
||||
return c.String(http.StatusInternalServerError, "Error resizing image")
|
||||
}
|
||||
|
||||
go func(data string) {
|
||||
if cc.redis == nil {
|
||||
return
|
||||
}
|
||||
|
||||
_, err = cc.redis.Set(context.TODO(), "latestImage:bin:"+latestImageVal, data, 600*time.Second).Result()
|
||||
if err != nil {
|
||||
c.Logger().Warn("could not cache image")
|
||||
}
|
||||
}(imageData)
|
||||
} else {
|
||||
c.Logger().Info("Image data fetched from cache")
|
||||
}
|
||||
|
||||
c.Response().Header().Set("Cache-Control", "public, max-age=600")
|
||||
|
||||
return c.Blob(http.StatusOK, "image/jpeg", []byte(imageData))
|
||||
}
|
||||
Reference in New Issue
Block a user