AnonymousOverflow/src/routes/home.go

79 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,
})
2022-12-27 23:53:28 -05:00
}
type urlConversionRequest struct {
URL string `form:"url" binding:"required"`
}
var coreRegex = regexp.MustCompile(`(?:https?://)?(?:www\.)?([^/]+)(/(?:questions|q|a)/.+)`)
// Will return `nil` if `rawUrl` is invalid.
func translateUrl(rawUrl string) string {
coreMatches := coreRegex.FindStringSubmatch(rawUrl)
if coreMatches == nil {
return ""
}
domain := coreMatches[1]
rest := coreMatches[2]
exchange := ""
if domain == "stackoverflow.com" {
// No exchange parameter needed.
} else if sub, found := strings.CutSuffix(domain, ".stackexchange.com"); found {
if sub == "" {
return ""
} else if strings.Contains(sub, ".") {
// Anything containing dots is interpreted as a full domain, so we use the correct full domain.
exchange = domain
} else {
exchange = sub
}
} else {
exchange = domain
}
// Ensure we properly format the return string to avoid double slashes
if exchange == "" {
return rest
} else {
return fmt.Sprintf("/exchange/%s%s", exchange, rest)
}
}
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",
})
return
}
translated := translateUrl(body.URL)
if translated == "" {
2022-12-27 23:53:28 -05:00
c.HTML(400, "home.html", gin.H{
"errorMessage": "Invalid stack overflow/exchange URL",
2022-12-27 23:53:28 -05:00
})
return
}
c.Redirect(302, translated)
2022-12-27 23:53:28 -05:00
}