From 29a5bfe9d91e38da7111b18c9318fee39b4a0b47 Mon Sep 17 00:00:00 2001 From: aotian16 Date: Wed, 26 Mar 2025 02:32:18 +0800 Subject: [PATCH] modify main.go --- backend/main.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/backend/main.go b/backend/main.go index 83de1fd..05b088d 100644 --- a/backend/main.go +++ b/backend/main.go @@ -278,4 +278,60 @@ func updateSitesOrderHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// 其他处理函数(addSiteHandler, deleteSiteHandler等)保持不变... \ No newline at end of file +func addSiteHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var s Site + if err := json.NewDecoder(r.Body).Decode(&s); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // 验证数据 + if s.Name == "" || s.URL == "" || s.Category == "" { + http.Error(w, "Name, URL and Category are required", http.StatusBadRequest) + return + } + + // 插入数据库 + res, err := db.Exec("INSERT INTO sites (name, url, icon, category) VALUES (?, ?, ?, ?)", + s.Name, s.URL, s.Icon, s.Category) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + id, _ := res.LastInsertId() + s.ID = int(id) + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(s) +} + +func deleteSiteHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + + var request struct { + ID int `json:"id"` + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + _, err := db.Exec("DELETE FROM sites WHERE id = ?", request.ID) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + w.WriteHeader(http.StatusOK) + fmt.Fprint(w, `{"status": "success"}`) +} \ No newline at end of file