forked from httpjamesm/AnonymousOverflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Redirect-short-links (httpjamesm#50)
* feat: redirect shortened URLs * feat: accept shortened URLs in converter * fix: tell resty not to follow redirect * fix: remove log
- Loading branch information
1 parent
4760681
commit 2ef7e05
Showing
4 changed files
with
53 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,4 +2,4 @@ | |
docker-compose.yml | ||
.DS_Store | ||
*bin | ||
/tmp | ||
/tmp |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
package routes | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"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() | ||
client.SetRedirectPolicy( | ||
resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error { | ||
return http.ErrUseLastResponse | ||
}), | ||
) | ||
|
||
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", | ||
"theme": c.MustGet("theme").(string), | ||
}) | ||
return | ||
} | ||
|
||
if resp.StatusCode() != 302 { | ||
c.HTML(400, "home.html", gin.H{ | ||
"errorMessage": fmt.Sprintf("Unexpected HTTP status from origin: %d", resp.StatusCode()), | ||
"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)) | ||
} |