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

@@ -26,10 +26,11 @@ var templates = template.Must(template.ParseFS(templateFiles, "templates/*.tpl")
type page struct {
Short string
URLs []*links.URL
}
func (srv *server) servePage(w http.ResponseWriter, p page) {
err := templates.ExecuteTemplate(w, "index.tpl", p)
func (srv *server) servePage(w http.ResponseWriter, p page, tpl string) {
err := templates.ExecuteTemplate(w, tpl, p)
if err != nil {
log.Printf("error executing template: %s", err)
http.Error(w, fmt.Sprintf("template execution failed: %s", err.Error()),
@@ -51,6 +52,12 @@ func (srv *server) postURL(w http.ResponseWriter, r *http.Request) {
return
}
url, err = links.CleanString(url)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
ctx := context.Background()
short, err := links.StoreURL(ctx, srv.db, url)
if err != nil {
@@ -58,7 +65,7 @@ func (srv *server) postURL(w http.ResponseWriter, r *http.Request) {
return
}
srv.servePage(w, page{Short: short})
srv.servePage(w, page{Short: short}, "index.tpl")
}
func (srv *server) redirect(w http.ResponseWriter, r *http.Request) {
@@ -72,6 +79,20 @@ func (srv *server) redirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, u, http.StatusFound)
}
func (srv *server) listAll(w http.ResponseWriter, r *http.Request) {
allPosts, err := links.FetchAll(context.Background(), srv.db)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
p := page{
URLs: allPosts,
}
srv.servePage(w, p, "list.tpl")
}
func (srv *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet && links.ValidShortCode.MatchString(r.URL.Path) {
srv.redirect(w, r)
@@ -94,5 +115,10 @@ func (srv *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
srv.servePage(w, page{})
if r.URL.Path == "/list" {
srv.listAll(w, r)
return
}
srv.servePage(w, page{}, "index.tpl")
}