AnonymousOverflow/src/routes/shortened.go

45 lines
1,018 B
Go
Raw Normal View History

2023-08-21 00:50:29 -04:00
package routes
import (
"fmt"
2023-08-21 00:56:39 -04:00
"net/http"
2023-08-21 00:50:29 -04:00
"os"
"github.com/gin-gonic/gin"
"github.com/go-resty/resty/v2"
)
func RedirectShortenedOverflowURL(c *gin.Context) {
id := c.Param("id")
// fetch the stack overflow URL
client := resty.New()
2023-08-21 00:56:39 -04:00
client.SetRedirectPolicy(
resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
}),
)
2023-08-21 00:50:29 -04:00
2023-08-21 00:56:39 -04:00
resp, err := client.R().Get(fmt.Sprintf("https://www.stackoverflow.com/a/%s", id))
2023-08-21 00:50:29 -04:00
if err != nil {
c.HTML(400, "home.html", gin.H{
"errorMessage": "Unable to fetch stack overflow URL",
"theme": c.MustGet("theme").(string),
})
return
}
if resp.StatusCode() != 302 {
c.HTML(400, "home.html", gin.H{
2023-08-21 00:56:39 -04:00
"errorMessage": fmt.Sprintf("Unexpected HTTP status from origin: %d", resp.StatusCode()),
2023-08-21 00:50:29 -04:00
"theme": c.MustGet("theme").(string),
})
return
}
// get the redirect URL
location := resp.Header().Get("Location")
c.Redirect(302, fmt.Sprintf("%s%s", os.Getenv("APP_URL"), location))
}