From 881b936377e833fa1d498f20c4e156832af2ef85 Mon Sep 17 00:00:00 2001 From: bear-brown-beard Date: Wed, 23 Oct 2024 20:23:28 +0500 Subject: [PATCH] 1th iteration --- precode.go | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/precode.go b/precode.go index d082d83..5b6e7aa 100644 --- a/precode.go +++ b/precode.go @@ -3,7 +3,7 @@ package main import ( "fmt" "net/http" - + "encoding/json" "github.com/go-chi/chi/v5" ) @@ -40,13 +40,68 @@ var tasks = map[string]Task{ } // Ниже напишите обработчики для каждого эндпоинта -// ... +func getTasks(w http.ResponseWriter, r *http.Request) { + resp, err := json.Marshal(tasks) + if err != nil { + http.Error(w, "Ошибка сервера", http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(resp) +} + +func postTasks(w http.ResponseWriter, r *http.Request) { + var task Task + err := json.NewDecoder(r.Body).Decode(&task) + if err != nil { + http.Error(w, "Ошибка при чтении JSON: "+err.Error(), http.StatusBadRequest) + return + } + if task.ID == "" { + http.Error(w, "Необходимо указать ID задачи", http.StatusBadRequest) + return + } + tasks[task.ID] = task + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) +} + +func getTasksId(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + task, ok := tasks[id] + if !ok { + http.Error(w, "Ошибка в поиске задачи", http.StatusNoContent) + return + } + resp, err := json.Marshal(task) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(resp) +} + +func deleteTasks(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + if _, exists := tasks[id]; !exists { + http.Error(w, "Команды не существует", http.StatusNotFound) + return + } + delete(tasks, id) + w.WriteHeader(http.StatusNoContent) +} func main() { r := chi.NewRouter() // здесь регистрируйте ваши обработчики - // ... + r.Get("/tasks", getTasks) + r.Post("/tasks", postTasks) + r.Get("/tasks/{id}", getTasksId) + r.Delete("/tasks/{id}", deleteTasks) if err := http.ListenAndServe(":8080", r); err != nil { fmt.Printf("Ошибка при запуске сервера: %s", err.Error())