From 3f1a3e308002892027cf2e6f9d77593f431e6826 Mon Sep 17 00:00:00 2001 From: Kamila Makasheva Date: Wed, 23 Oct 2024 22:15:16 +0500 Subject: [PATCH] Four endpoints CCRD --- precode.go | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 5 deletions(-) diff --git a/precode.go b/precode.go index d082d83..3dc0c0b 100644 --- a/precode.go +++ b/precode.go @@ -1,13 +1,14 @@ package main import ( + "bytes" + "encoding/json" "fmt" "net/http" "github.com/go-chi/chi/v5" ) -// Task ... type Task struct { ID string `json:"id"` Description string `json:"description"` @@ -39,14 +40,75 @@ var tasks = map[string]Task{ }, } -// Ниже напишите обработчики для каждого эндпоинта -// ... +func getTasks(w http.ResponseWriter, r *http.Request) { + resp, err := json.Marshal(tasks) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + w.Write(resp) +} + +func PostTask(w http.ResponseWriter, r *http.Request) { + var task Task + var buf bytes.Buffer + + _, err := buf.ReadFrom(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + } + + err = json.Unmarshal(buf.Bytes(), &task) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + } + tasks[task.ID] = task + + w.WriteHeader(http.StatusCreated) + +} + +func GetTask(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + task, ok := tasks[id] + if !ok { + http.Error(w, "Task not found", http.StatusBadRequest) + 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 DeleteTask(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + + _, ok := tasks[id] + if !ok { + http.Error(w, "Task not found", http.StatusBadRequest) + return + } + + delete(tasks, id) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) +} func main() { r := chi.NewRouter() - // здесь регистрируйте ваши обработчики - // ... + r.Get("/tasks", getTasks) + r.Post("/tasks", PostTask) + r.Get("/tasks/{id}", GetTask) + r.Delete("/tasks/{id}", DeleteTask) if err := http.ListenAndServe(":8080", r); err != nil { fmt.Printf("Ошибка при запуске сервера: %s", err.Error())