AnonymousOverflow/src/routes/home.go

64 lines
1.6 KiB
Go
Raw Normal View History

2022-12-27 23:53:28 -05:00
package routes
import (
2022-12-28 11:33:26 -05:00
"anonymousoverflow/config"
2022-12-27 23:53:28 -05:00
"fmt"
"regexp"
2022-12-27 23:53:28 -05:00
"strings"
"github.com/gin-gonic/gin"
)
func GetHome(c *gin.Context) {
2022-12-28 11:33:26 -05:00
c.HTML(200, "home.html", gin.H{
"version": config.Version,
"theme": c.MustGet("theme").(string),
2022-12-28 11:33:26 -05:00
})
2022-12-27 23:53:28 -05:00
}
type urlConversionRequest struct {
URL string `form:"url" binding:"required"`
}
var stackExchangeRegex = regexp.MustCompile(`https://(.+).stackexchange.com/questions/`)
2022-12-27 23:53:28 -05:00
func PostHome(c *gin.Context) {
body := urlConversionRequest{}
if err := c.ShouldBind(&body); err != nil {
c.HTML(400, "home.html", gin.H{
"errorMessage": "Invalid request body",
"theme": c.MustGet("theme").(string),
2022-12-27 23:53:28 -05:00
})
return
}
soLink := body.URL
// remove the www.
soLink = strings.ReplaceAll(soLink, "www.", "")
2022-12-27 23:53:28 -05:00
// validate URL
isStackOverflow := strings.HasPrefix(soLink, "https://stackoverflow.com/questions/")
isShortenedStackOverflow := strings.HasPrefix(soLink, "https://stackoverflow.com/a/")
isStackExchange := stackExchangeRegex.MatchString(soLink)
if !isStackExchange && !isStackOverflow && !isShortenedStackOverflow {
2022-12-27 23:53:28 -05:00
c.HTML(400, "home.html", gin.H{
"errorMessage": "Invalid stack overflow/exchange URL",
"theme": c.MustGet("theme").(string),
2022-12-27 23:53:28 -05:00
})
return
}
// if stack overflow, trim https://stackoverflow.com
if isStackOverflow || isShortenedStackOverflow {
c.Redirect(302, strings.TrimPrefix(soLink, "https://stackoverflow.com"))
return
}
// if stack exchange, extract the subdomain
sub := stackExchangeRegex.FindStringSubmatch(soLink)[1]
2022-12-27 23:53:28 -05:00
c.Redirect(302, fmt.Sprintf("/exchange/%s/%s", sub, strings.TrimPrefix(soLink, fmt.Sprintf("https://%s.stackexchange.com", sub))))
2022-12-27 23:53:28 -05:00
}