Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

first commit #159

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 67 additions & 3 deletions precode.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"

Expand Down Expand Up @@ -40,13 +42,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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_ , _ = w.Write(resp)
тут стоит либо явно проигнорировать ошибку или ее логировать

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут вообще не понял, о чем вы

}

func postTasks(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)
return
}

if err = json.Unmarshal(buf.Bytes(), &task); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

tasks[task.ID] = task

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тут нужно проверить что такой задачи нет в tasks и если есть вернуть ошибку


w.Header().Set("Content-Type", "application/json")
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, "Задание не найдено!!", http.StatusBadRequest)
return
}
resp, err := json.Marshal(task)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}

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")

if _, ok := tasks[id]; !ok {
http.Error(w, "Задание не найдено!!!", http.StatusBadRequest)
return
}
delete(tasks, id)

w.WriteHeader(http.StatusOK)
}

func main() {
r := chi.NewRouter()

// здесь регистрируйте ваши обработчики
// ...
r.Get("/tasks", getTasks)
r.Post("/tasks", postTasks)
r.Get("/tasks/{id}", getTask)
r.Delete("/tasks/{id}", deleteTask)

if err := http.ListenAndServe(":8080", r); err != nil {
fmt.Printf("Ошибка при запуске сервера: %s", err.Error())
Expand Down