delete short url

This commit is contained in:
kenneth
2023-12-25 17:31:07 +08:00
parent c1f4731669
commit ae060a2a37
10 changed files with 132 additions and 12 deletions

View File

@@ -15,14 +15,6 @@ func HomeView(templates fs.FS, store db.Store) http.HandlerFunc {
if err != nil {
renderLayout(w, r, templates, nil, "home.html.tmpl")
}
scheme := "http://"
if r.TLS != nil {
scheme = "https://"
}
for _, item := range result {
item.ShortUrl = scheme + r.Host + "/" + item.ShortUrl
}
renderLayout(w, r, templates, result, "home.html.tmpl")
}
}

View File

@@ -20,6 +20,13 @@ func renderLayout(w http.ResponseWriter, r *http.Request, templates fs.FS, data
"currentUser": func() *Authorize {
return withUser(r.Context())
},
"genShortUrl": func(url string) string {
scheme := "http://"
if r.TLS != nil {
scheme = "https://"
}
return scheme + r.Host + "/" + url
},
})
tpl := template.Must(t.Clone())

35
handler/resp.go Normal file
View File

@@ -0,0 +1,35 @@
package handler
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
)
type response struct {
Success bool `json:"success"`
Message string `json:"message"`
Data any `json:"data"`
}
func respond(w http.ResponseWriter, message string, v any, statusCode int) {
rsp := response{
Success: true,
Message: message,
Data: v,
}
b, err := json.Marshal(rsp)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
_, err = w.Write(b)
if err != nil && !errors.Is(err, context.Canceled) {
log.Printf("could not write http response: %v\n", err)
}
}

View File

@@ -59,6 +59,28 @@ func CreateShortUrl(templates fs.FS, store db.Store) http.HandlerFunc {
}
}
func DeleteShortUrl(store db.Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
shorUrl := vars["shortUrl"]
_, err := store.UpdateStatus(r.Context(), &db.UpdateStatusParams{
ShortUrl: shorUrl,
Status: -1,
})
if err != nil {
respond(w, "删除错误", nil, http.StatusOK)
return
}
err = service.DeleteShortUrl(shorUrl)
if err != nil {
respond(w, "删除错误", nil, http.StatusOK)
return
}
respond(w, "删除成功", nil, http.StatusOK)
}
}
func HandleShortUrlRedirect(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
shorUrl := vars["shortUrl"]