package handler import ( "net/http" "time" "github.com/gorilla/mux" "github.com/zhang2092/go-url-shortener/internal/db" "github.com/zhang2092/go-url-shortener/internal/middleware" "github.com/zhang2092/go-url-shortener/internal/service" "github.com/zhang2092/go-url-shortener/internal/shortener" "github.com/zhang2092/go-url-shortener/internal/templ" ) func CreateShortUrlView(w http.ResponseWriter, r *http.Request) { templ.CreateUrl(w, r, "") } func CreateShortUrl(store db.Store) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() if err := r.ParseForm(); err != nil { templ.CreateUrl(w, r, "请求参数错误") return } ctx := r.Context() user := middleware.GetUser(ctx) longUrl := r.PostFormValue("long_url") shortUrl, err := shortener.GenerateShortLink(longUrl, user.ID) if err != nil { templ.CreateUrl(w, r, "生成短路径错误") return } _, err = store.CreateUserUrl(ctx, &db.CreateUserUrlParams{ UserID: user.ID, ShortUrl: shortUrl, OriginUrl: longUrl, ExpireAt: time.Now().Add(time.Hour * 6), }) if err != nil { templ.CreateUrl(w, r, "短路径存储错误") return } err = service.SaveUrlMapping(shortUrl, longUrl, user.ID) if err != nil { templ.CreateUrl(w, r, "短路径存储错误") return } http.Redirect(w, r, "/", http.StatusFound) } } 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 { RespondErr(w, "删除错误", nil) return } err = service.DeleteShortUrl(shorUrl) if err != nil { RespondErr(w, "删除错误", nil) return } respond(w, "删除成功", nil, http.StatusOK) } } func HandleShortUrlRedirect(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) shorUrl := vars["shortUrl"] link, err := service.RetrieveInitialUrl(shorUrl) if err != nil || len(link) == 0 { RespondErr(w, "短链已经失效", nil) return } http.Redirect(w, r, link, http.StatusFound) }