From 7fa26139bc12b71763260c943218235e4921932b Mon Sep 17 00:00:00 2001 From: httpjamesm Date: Mon, 21 Aug 2023 00:56:39 -0400 Subject: [PATCH] fix: tell resty not to follow redirect --- .gitignore | 3 ++- src/routes/home.go | 8 ++++---- src/routes/shortened.go | 13 +++++++++++-- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index 2531ed9..a2dfaeb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .env docker-compose.yml .DS_Store -*bin \ No newline at end of file +*bin +main \ No newline at end of file diff --git a/src/routes/home.go b/src/routes/home.go index 1eb3fb0..27b511a 100644 --- a/src/routes/home.go +++ b/src/routes/home.go @@ -35,6 +35,9 @@ func PostHome(c *gin.Context) { soLink := body.URL + // remove the www. + soLink = strings.ReplaceAll(soLink, "www.", "") + // validate URL isStackOverflow := strings.HasPrefix(soLink, "https://stackoverflow.com/questions/") isShortenedStackOverflow := strings.HasPrefix(soLink, "https://stackoverflow.com/a/") @@ -48,12 +51,9 @@ func PostHome(c *gin.Context) { } // if stack overflow, trim https://stackoverflow.com - if isStackOverflow { + if isStackOverflow || isShortenedStackOverflow { c.Redirect(302, strings.TrimPrefix(soLink, "https://stackoverflow.com")) return - } else if isShortenedStackOverflow { - c.Redirect(302, strings.TrimPrefix(soLink, "https://stackoverflow.com/a/")) - return } // if stack exchange, extract the subdomain diff --git a/src/routes/shortened.go b/src/routes/shortened.go index 73e1b34..7e38e29 100644 --- a/src/routes/shortened.go +++ b/src/routes/shortened.go @@ -2,6 +2,8 @@ package routes import ( "fmt" + "log" + "net/http" "os" "github.com/gin-gonic/gin" @@ -13,8 +15,13 @@ func RedirectShortenedOverflowURL(c *gin.Context) { // fetch the stack overflow URL client := resty.New() + client.SetRedirectPolicy( + resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + }), + ) - resp, err := client.R().Get(fmt.Sprintf("https://stackoverflow.com/a/%s", id)) + resp, err := client.R().Get(fmt.Sprintf("https://www.stackoverflow.com/a/%s", id)) if err != nil { c.HTML(400, "home.html", gin.H{ "errorMessage": "Unable to fetch stack overflow URL", @@ -23,9 +30,11 @@ func RedirectShortenedOverflowURL(c *gin.Context) { return } + log.Println(resp.String()) + if resp.StatusCode() != 302 { c.HTML(400, "home.html", gin.H{ - "errorMessage": "Unexpected HTTP status from origin", + "errorMessage": fmt.Sprintf("Unexpected HTTP status from origin: %d", resp.StatusCode()), "theme": c.MustGet("theme").(string), }) return