From 0339f10a64b4ed92a3c6532e9e9be33b83688c14 Mon Sep 17 00:00:00 2001 From: SnO2WMaN Date: Fri, 8 Dec 2023 18:36:50 +0900 Subject: [PATCH] proxy --- main.go | 2 ++ proxy.go | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 proxy.go diff --git a/main.go b/main.go index 11d647b..2614a05 100644 --- a/main.go +++ b/main.go @@ -20,6 +20,8 @@ func main() { e.GET("/mads/:serial/primary", MADPrimaryThumbnail) + e.GET("/proxy", Proxy) + e.GET("/original/youtube/:vid", OriginalYoutubeThumbnail) e.GET("/original/nicovideo/:vid", OriginalNicovideoThumbnail) e.GET("/original/bilibili/:vid", OriginalBilibiliThumbnail) diff --git a/proxy.go b/proxy.go new file mode 100644 index 0000000..180dc20 --- /dev/null +++ b/proxy.go @@ -0,0 +1,52 @@ +package main + +import ( + "encoding/base64" + "fmt" + "net/http" + "os" + "time" + + "github.com/labstack/echo/v4" + "github.com/redis/go-redis/v9" +) + +func Proxy(c echo.Context) error { + url := c.FormValue("url") + if url == "" { + return c.String(http.StatusBadRequest, "Bad request at url") + } + + scale := c.FormValue("scale") + if scale == "" { + return c.String(http.StatusBadRequest, "Bad request at scale") + } + width, height, err := ParseScale(scale) + if err != nil { + return c.String(http.StatusBadRequest, err.Error()) + } + + rdb := redis.NewClient(&redis.Options{Addr: os.Getenv("REDIS_ADDRESS")}) + defer rdb.Close() + + redisKey := fmt.Sprintf("proxy_%s_%d_%d", url, width, height) + cachedUrl, err := rdb.Get(ctx, redisKey).Result() + if err != nil && err != redis.Nil { + c.Logger().Error(err) + return c.String(http.StatusInternalServerError, "Internal Server Error") + } + if cachedUrl != "" { + return c.Redirect(http.StatusTemporaryRedirect, cachedUrl) + } + + proxiedUrl := SignURL( + fmt.Sprintf("/rs:fit:%d:%d:1:1/background:000000/%s", width, height, base64.URLEncoding.EncodeToString([]byte(url)))) + c.Logger().Debug(proxiedUrl) + + err = rdb.Set(ctx, redisKey, proxiedUrl, time.Duration(600*time.Second)).Err() + if err != nil { + c.Logger().Error(err) + } + + return c.Redirect(http.StatusTemporaryRedirect, proxiedUrl) +}