You've already forked go-url-shortener
delete short url
This commit is contained in:
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
35
handler/resp.go
Normal 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)
|
||||
}
|
||||
}
|
||||
@@ -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"]
|
||||
|
||||
Reference in New Issue
Block a user