diff --git a/precode.go b/precode.go index d082d83..56b35ef 100644 --- a/precode.go +++ b/precode.go @@ -1,6 +1,8 @@ package main import ( + "bytes" + "encoding/json" "fmt" "net/http" @@ -42,11 +44,80 @@ var tasks = map[string]Task{ // Ниже напишите обработчики для каждого эндпоинта // ... +func getVse(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 postZad(w http.ResponseWriter, r *http.Request) { + var zad Task + var buf bytes.Buffer + + _, err := buf.ReadFrom(r.Body) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + if err = json.Unmarshal(buf.Bytes(), &zad); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + tasks[zad.ID] = zad + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) +} + +func getZad(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + zad, ok := tasks[id] + if !ok { + http.Error(w, "zadachi net", http.StatusBadRequest) + return + } + resp, err := json.Marshal(zad) + 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 delZad(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + _, ok := tasks[id] + if !ok { + http.Error(w, "zadachi net", http.StatusBadRequest) + return + } + delete(tasks, id) + resp, err := json.Marshal(tasks) + 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 main() { r := chi.NewRouter() // здесь регистрируйте ваши обработчики // ... + r.Get("/tasks", getVse) + r.Post("/tasks", postZad) + r.Get("/tasks/{id}", getZad) + r.Delete("/tasks/{id}", delZad) if err := http.ListenAndServe(":8080", r); err != nil { fmt.Printf("Ошибка при запуске сервера: %s", err.Error())