-
Notifications
You must be signed in to change notification settings - Fork 314
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
lool #182
base: main
Are you sure you want to change the base?
lool #182
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" | ||
|
||
|
@@ -40,13 +42,99 @@ var tasks = map[string]Task{ | |
} | ||
|
||
// Ниже напишите обработчики для каждого эндпоинта | ||
// ... | ||
|
||
// обработчик 1 | ||
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) | ||
_, err = w.Write(resp) | ||
if err != nil { | ||
fmt.Println("failed to write responce", err.Error()) | ||
return | ||
} | ||
} | ||
|
||
// обработчик 2 | ||
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.StatusInternalServerError) | ||
return | ||
} | ||
if err = json.Unmarshal(buf.Bytes(), &task); err != nil { | ||
http.Error(w, err.Error(), http.StatusBadRequest) | ||
return | ||
} | ||
if _, ex := tasks[task.ID]; ex { | ||
http.Error(w, "Задача с таким ID уже существует", http.StatusConflict) | ||
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.
Спасибо за фичу. Учту в следующих проектах. |
||
return | ||
} | ||
|
||
tasks[task.ID] = 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. Перед этой операцией полезно добавить проверку - есть ли уже такой ID. И если да - вернуть ошибку пользователю. Иначе задача может быть перезатерта 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.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(http.StatusCreated) | ||
} | ||
|
||
// обработчик 3 | ||
func getTaskForId(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.StatusInternalServerError) | ||
return | ||
} | ||
w.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(http.StatusOK) | ||
|
||
_, err = w.Write(resp) | ||
if err != nil { | ||
fmt.Printf("Ошибка записи: %v", err) | ||
} | ||
|
||
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. Пустую строчку можно совсем убрать |
||
} | ||
|
||
// обработчик 4 | ||
func taskDel(w http.ResponseWriter, r *http.Request) { | ||
id := chi.URLParam(r, "id") | ||
|
||
_, ok := tasks[id] | ||
if !ok { | ||
http.Error(w, "Не удалось удалить задачу. Отсутствует запрашиваемая задача.", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
delete(tasks, id) | ||
|
||
w.Header().Set("Content-Type", "application/json") | ||
w.WriteHeader(http.StatusOK) | ||
} | ||
|
||
func main() { | ||
r := chi.NewRouter() | ||
|
||
// здесь регистрируйте ваши обработчики | ||
// ... | ||
//обработчик 1 | ||
r.Get("/tasks", getTasks) | ||
//обработчик 2 | ||
r.Post("/tasks", postTask) | ||
//обработчик 3 | ||
r.Get("/tasks/{id}", getTaskForId) | ||
//обработчик 4 | ||
r.Delete("/tasks/{id}", taskDel) | ||
|
||
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.
Круто что проверяешь ошибки явно
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.
^^
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.
Класная телега у тебя. кстати. Подписался)
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.
Рада. Добро пожаловать!