-
Notifications
You must be signed in to change notification settings - Fork 310
rabotaet #220
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
base: main
Are you sure you want to change the base?
rabotaet #220
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. _ , _ = w.Write(resp)
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Поясните, пожалуйста. Распишите подробно, что нужно сделать, с примерами, пожалуйста. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @artwovk прошу прощения упустил вопрос потому, что PR был другой отправлен в следующую итерацию ревью работа с ошибками это очень важная особенность программирования на go если функция возвращает ошибку ее принято обработать например в данной конкретно ситуации если ошибка из функции w.Write мы уже не сможем вернуть ответ на запрос пользователя - так как ошибка при записи тела ответа поэтому либо явно игнорируем ее _ , _ = w.Write(resp) - такая конструкция говорит о том что разработчик в курсе что функция возвращает ошибку и сознательно ее игнорирует либо логируем например так |
||
| } | ||
|
|
||
| func postZad(w http.ResponseWriter, r *http.Request) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. addTask |
||
| var zad Task | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. сначала нужно проверить что такой задачи еще нет - и если есть вернуть ошибку
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Можно, пожалуйста, ссылку на урок, где нас этому учат? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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) { | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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()) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
getTasks