diff --git a/handler.go b/handler.go index 9400746..1517d4d 100644 --- a/handler.go +++ b/handler.go @@ -5,6 +5,7 @@ import ( "database/sql" "embed" "net/http" + "regexp" "strings" "git.wntrmute.dev/mc/mcdsl/auth" @@ -82,6 +83,14 @@ func (srv *server) postURL(w http.ResponseWriter, r *http.Request) { return } + customShort := strings.TrimSpace(r.FormValue("custom")) + if customShort != "" { + if !regexp.MustCompile(`^[a-zA-Z0-9]+$`).MatchString(customShort) { + http.Error(w, "custom short code must be letters and numbers only", http.StatusBadRequest) + return + } + } + url, err = links.CleanString(url, stripQuery) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -89,7 +98,7 @@ func (srv *server) postURL(w http.ResponseWriter, r *http.Request) { } ctx := context.Background() - short, err := links.StoreURL(ctx, srv.db, url) + short, err := links.StoreURL(ctx, srv.db, url, customShort) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/links/url.go b/links/url.go index 318f4de..912a78c 100644 --- a/links/url.go +++ b/links/url.go @@ -134,14 +134,16 @@ func Lookup(ctx context.Context, db *sql.DB, s string) (string, error) { return short, nil } -func StoreURL(ctx context.Context, db *sql.DB, s string) (string, error) { - short, err := Lookup(ctx, db, s) - if err == nil { - return short, nil - } +func StoreURL(ctx context.Context, db *sql.DB, s string, customShort string) (string, error) { + if customShort == "" { + short, err := Lookup(ctx, db, s) + if err == nil { + return short, nil + } - if err != sql.ErrNoRows { - return "", err + if err != sql.ErrNoRows { + return "", err + } } u, err := FromString(s) @@ -149,6 +151,10 @@ func StoreURL(ctx context.Context, db *sql.DB, s string) (string, error) { return "", err } + if customShort != "" { + u.Short = customShort + } + err = u.Store(ctx, db) if err != nil { return "", err diff --git a/templates/index.html b/templates/index.html index 932c9b5..178422d 100644 --- a/templates/index.html +++ b/templates/index.html @@ -13,6 +13,10 @@ +
+ + +