clean URLs by default

This commit is contained in:
2022-03-20 15:03:39 -07:00
parent 8756e3deb8
commit 7285264fed
3 changed files with 114 additions and 4 deletions

View File

@@ -22,6 +22,10 @@ type URL struct {
CreatedAt time.Time
}
func (u *URL) Timestamp() string {
return u.CreatedAt.Format("2006-01-02 15:04")
}
func (u *URL) Store(ctx context.Context, db *pgxpool.Pool) error {
stmt := psql.Insert("urls").
Columns("id", "url", "nurl", "short", "created_at").
@@ -56,6 +60,29 @@ func NormalizeString(s string) (string, error) {
return u.String(), nil
}
// Clean should scrub out junk from the URL.
func Clean(u *url.URL) *url.URL {
norm := &url.URL{
Scheme: u.Scheme,
Host: u.Host,
Path: u.Path,
RawPath: u.RawPath,
Fragment: u.Fragment,
RawFragment: u.RawFragment,
}
return norm
}
func CleanString(s string) (string, error) {
u, err := url.Parse(s)
if err != nil {
return "", err
}
u = Clean(u)
return u.String(), nil
}
func New(u *url.URL) *URL {
link := &URL{
ID: uuid.NewString(),
@@ -144,3 +171,35 @@ func RetrieveURL(ctx context.Context, db *pgxpool.Pool, short string) (string, e
return url, nil
}
func FetchAll(ctx context.Context, db *pgxpool.Pool) ([]*URL, error) {
stmt := psql.Select("*").From("urls").OrderBy("created_at")
query, args, err := stmt.ToSql()
if err != nil {
return nil, err
}
rows, err := db.Query(ctx, query, args...)
if err != nil {
return nil, err
}
var urls []*URL
for rows.Next() {
u := &URL{}
err = rows.Scan(
&u.ID,
&u.URL,
&u.NURL,
&u.Short,
&u.CreatedAt,
)
if err != nil {
return nil, err
}
urls = append(urls, u)
}
return urls, nil
}