1
0
mirror of https://github.com/taigrr/shorturl synced 2025-01-18 04:03:16 -08:00

Handle delete URL

This commit is contained in:
srxr 2021-03-27 07:11:42 +00:00
parent e984fce524
commit f65255f6eb
No known key found for this signature in database
GPG Key ID: 5F5DB27AF89FA243
2 changed files with 40 additions and 0 deletions

View File

@ -61,3 +61,19 @@ func (u *URL) update(target string) error {
u.UpdatedAt = time.Now() u.UpdatedAt = time.Now()
return db.Update(u) return db.Update(u)
} }
func del(id string) error {
var u URL
err := db.One("ID", id, &u)
if err != nil {
return err
}
err = db.DeleteStruct(&u)
if err != nil {
return err
}
return nil
}

View File

@ -296,6 +296,29 @@ func (s *Server) ListenAndServe() {
) )
} }
// DeleteHandler ...
func (s *Server) DeleteHandler() httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
id := p.ByName("id")
if id == "" {
http.Error(w, "Bad Request", http.StatusBadRequest)
return
}
err := del(id)
if err != nil {
log.Printf("error delete id: %s: %v", id, err)
http.Error(w, "Iternal Error", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
return
}
}
func (s *Server) initRoutes() { func (s *Server) initRoutes() {
s.router.Handler("GET", "/debug/metrics", exp.ExpHandler(s.counters.r)) s.router.Handler("GET", "/debug/metrics", exp.ExpHandler(s.counters.r))
s.router.GET("/debug/stats", s.StatsHandler()) s.router.GET("/debug/stats", s.StatsHandler())
@ -316,6 +339,7 @@ func (s *Server) initRoutes() {
s.router.GET("/r/:id", s.RedirectHandler()) s.router.GET("/r/:id", s.RedirectHandler())
s.router.GET("/e/:id", s.EditHandler()) s.router.GET("/e/:id", s.EditHandler())
s.router.POST("/e/:id", s.UpdateHandler()) s.router.POST("/e/:id", s.UpdateHandler())
s.router.GET("/d/:id", s.DeleteHandler())
} }
// NewServer ... // NewServer ...