diff --git a/handler/resp.go b/handler/resp.go index a470710..f86d78b 100644 --- a/handler/resp.go +++ b/handler/resp.go @@ -33,3 +33,23 @@ func respond(w http.ResponseWriter, message string, v any, statusCode int) { log.Printf("could not write http response: %v\n", err) } } + +func RespondErr(w http.ResponseWriter, message string, v any) { + rsp := response{ + Success: false, + 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(http.StatusInternalServerError) + _, err = w.Write(b) + if err != nil && !errors.Is(err, context.Canceled) { + log.Printf("could not write http response: %v\n", err) + } +} diff --git a/handler/short_url.go b/handler/short_url.go index f6b8be7..b82799a 100644 --- a/handler/short_url.go +++ b/handler/short_url.go @@ -68,12 +68,12 @@ func DeleteShortUrl(store db.Store) http.HandlerFunc { Status: -1, }) if err != nil { - respond(w, "删除错误", nil, http.StatusOK) + RespondErr(w, "删除错误", nil) return } err = service.DeleteShortUrl(shorUrl) if err != nil { - respond(w, "删除错误", nil, http.StatusOK) + RespondErr(w, "删除错误", nil) return }