fixed url validation

This commit is contained in:
4rkal 2024-09-12 21:10:09 +03:00
parent d1f48ae00e
commit 64dcf4614e
3 changed files with 28 additions and 4 deletions

View File

@ -5,6 +5,8 @@ import (
"math/rand" "math/rand"
"net/http" "net/http"
"net/url" "net/url"
"regexp"
"strings"
"time" "time"
"github.com/4rkal/shortr/models" "github.com/4rkal/shortr/models"
@ -50,6 +52,10 @@ func RedirectHandler(c echo.Context) error {
return c.String(http.StatusNotFound, "Link not found") return c.String(http.StatusNotFound, "Link not found")
} }
if !strings.Contains(link.Url, "://") {
link.Url = "http://" + link.Url
}
link.Clicks = link.Clicks + 1 link.Clicks = link.Clicks + 1
return c.Redirect(http.StatusMovedPermanently, link.Url) return c.Redirect(http.StatusMovedPermanently, link.Url)
@ -102,8 +108,26 @@ func StatsSubmissionHandler(c echo.Context) error {
} }
func isURL(s string) bool { func isURL(s string) bool {
_, err := url.ParseRequestURI(s) if !strings.Contains(s, "://") {
return err == nil s = "http://" + s
}
parsedUrl, err := url.ParseRequestURI(s)
if err != nil {
return false
}
if parsedUrl.Host == "" {
return false
}
domainRegex := `^([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}$`
matched, err := regexp.MatchString(domainRegex, parsedUrl.Host)
if err != nil || !matched {
return false
}
return true
} }
func generateRandomString(length int) string { func generateRandomString(length int) string {

View File

@ -7,7 +7,7 @@ templ Index(){
<h1>Blazingly fast URL shortener</h1> <h1>Blazingly fast URL shortener</h1>
<p>Shorten URLs and track clicks</p> <p>Shorten URLs and track clicks</p>
<form action="/submit" method="post"> <form action="/submit" method="post">
<input type="url" id="url" name="url" placeholder="Enter URL here..."> <input type="text" id="url" name="url" placeholder="Enter URL here...">
<button type="submit">Shorten URL</button> <button type="submit">Shorten URL</button>
</form> </form>
</div> </div>

View File

@ -41,7 +41,7 @@ func Index() templ.Component {
}() }()
} }
ctx = templ.InitializeContext(ctx) ctx = templ.InitializeContext(ctx)
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<div class=\"card\"><h1>Blazingly fast URL shortener</h1><p>Shorten URLs and track clicks</p><form action=\"/submit\" method=\"post\"><input type=\"url\" id=\"url\" name=\"url\" placeholder=\"Enter URL here...\"> <button type=\"submit\">Shorten URL</button></form></div>") _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString("<div class=\"card\"><h1>Blazingly fast URL shortener</h1><p>Shorten URLs and track clicks</p><form action=\"/submit\" method=\"post\"><input type=\"text\" id=\"url\" name=\"url\" placeholder=\"Enter URL here...\"> <button type=\"submit\">Shorten URL</button></form></div>")
if templ_7745c5c3_Err != nil { if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err return templ_7745c5c3_Err
} }