Skip to content
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
71 changes: 71 additions & 0 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 @@ -42,11 +44,80 @@ var tasks = map[string]Task{
// Ниже напишите обработчики для каждого эндпоинта
// ...

func getVse(w http.ResponseWriter, r *http.Request) {

Choose a reason for hiding this comment

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

getTasks

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.

Поясните, пожалуйста. Распишите подробно, что нужно сделать, с примерами, пожалуйста.

Choose a reason for hiding this comment

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

@artwovk прошу прощения упустил вопрос потому, что PR был другой отправлен в следующую итерацию ревью

работа с ошибками это очень важная особенность программирования на go

если функция возвращает ошибку ее принято обработать например

if _ , err := w.Write(resp); err != nil {
    ...
}

в данной конкретно ситуации если ошибка из функции w.Write мы уже не сможем вернуть ответ на запрос пользователя - так как ошибка при записи тела ответа

поэтому либо явно игнорируем ее _ , _ = w.Write(resp) - такая конструкция говорит о том что разработчик в курсе что функция возвращает ошибку и сознательно ее игнорирует

либо логируем например так

if _ , err := w.Write(resp); err != nil {
    log.Print(err)
}

}

func postZad(w http.ResponseWriter, r *http.Request) {

Choose a reason for hiding this comment

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

addTask

var zad Task

Choose a reason for hiding this comment

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

названия переменным нужно выбирать так чтобы они несли какой то смысл

не стоит использовать сокращения и транслитерацию

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(), &zad); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
tasks[zad.ID] = zad

Choose a reason for hiding this comment

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

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

Copy link
Author

Choose a reason for hiding this comment

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

Можно, пожалуйста, ссылку на урок, где нас этому учат?
Я не нашёл информации.

Choose a reason for hiding this comment

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

@artwovk чему? как проверить есть ли ключ в мапе? ну так я понимаю с этим нет проблем на 96 ты это делаешь.

или тому добавить не равно изменить? тут ответ ожидается http.StatusCreated - что подразумевает добавление чего то - да и в задании так описано


w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
}

func getZad(w http.ResponseWriter, r *http.Request) {

Choose a reason for hiding this comment

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

getTask

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

Choose a reason for hiding this comment

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

deleteTasks

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())
Expand Down