fix: tell resty not to follow redirect

This commit is contained in:
httpjamesm
2023-08-21 00:56:39 -04:00
parent 6c7f8248e7
commit 7fa26139bc
3 changed files with 17 additions and 7 deletions
+2 -1
View File
@@ -1,4 +1,5 @@
.env
docker-compose.yml
.DS_Store
*bin
*bin
main
+4 -4
View File
@@ -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
+11 -2
View File
@@ -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