-
Notifications
You must be signed in to change notification settings - Fork 310
First iteration #206
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?
First iteration #206
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,92 @@ var tasks = map[string]Task{ | |
| } | ||
|
|
||
| // Ниже напишите обработчики для каждого эндпоинта | ||
| // ... | ||
|
|
||
| // Обработчик для всех задач (метод GET) endpoint /tasks | ||
| func allTasks(res http.ResponseWriter, req *http.Request) { | ||
|
|
||
| resp, err := json.Marshal(tasks) | ||
| if err != nil { | ||
| http.Error(res, err.Error(), http.StatusInternalServerError) | ||
| return | ||
| } | ||
| res.Header().Set("Content-type", "application/json") | ||
| res.WriteHeader(http.StatusOK) | ||
| _, _ = res.Write(resp) | ||
| } | ||
|
|
||
| // Обработчик для отаправки запросов на сервер (метод Post) endpoint /tasks | ||
| func postTasks(res http.ResponseWriter, req *http.Request) { | ||
|
|
||
| var task Task | ||
| var buff bytes.Buffer | ||
|
|
||
| _, err := buff.ReadFrom(req.Body) | ||
| if err != nil { | ||
| http.Error(res, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| if err = json.Unmarshal(buff.Bytes(), &task); err != nil { | ||
| http.Error(res, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
| // Здесь проверяем начличие задачи | ||
| if _, exists := tasks[task.ID]; exists { | ||
| http.Error(res, "Эта задача уже существует", http.StatusBadRequest) | ||
| return | ||
| } | ||
| tasks[task.ID] = task | ||
| res.Header().Set("Content-type", "application/json") | ||
| res.WriteHeader(http.StatusCreated) | ||
| } | ||
|
|
||
| // Обработчик для получения задач по ID (метод GET) endpoint /tasks/{id} | ||
| func idTasks(res http.ResponseWriter, req *http.Request) { | ||
| id := chi.URLParam(req, "id") | ||
| task, ok := tasks[id] | ||
| if !ok { | ||
| // Здесь проверяем начличие задачи | ||
| http.Error(res, "Задача не найдена", http.StatusNoContent) | ||
| return | ||
| } | ||
|
|
||
| resp, err := json.Marshal(task) | ||
| if err != nil { | ||
| // Здесь возвращаем ошибку в соответствии с заданием | ||
| http.Error(res, err.Error(), http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| res.Header().Set("Content-type", "application/json") | ||
| res.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. _, _ = res.Write(resp) |
||
| } | ||
|
|
||
| // Обработчик удаления задач по ID (метод DELETE) endpoint /tasks/{id} | ||
| func delTasks(res http.ResponseWriter, req *http.Request) { | ||
| id := chi.URLParam(req, "id") | ||
| _, ok := tasks[id] | ||
| if !ok { | ||
| // Здесь проверяем наличие задачи | ||
| http.Error(res, "Задача не найдена", http.StatusNoContent) | ||
| return | ||
| } | ||
|
|
||
| delete(tasks, id) | ||
| res.Header().Set("Content-type", "application/json") | ||
| // Возвращем статус в соответствии с заданием | ||
| res.WriteHeader(http.StatusOK) | ||
| } | ||
|
|
||
| func main() { | ||
| r := chi.NewRouter() | ||
|
|
||
| // здесь регистрируйте ваши обработчики | ||
| // ... | ||
| r.Get("/tasks", allTasks) | ||
|
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. getTasks |
||
| r.Post("/tasks", postTasks) | ||
|
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 |
||
| r.Get("/tasks/{id}", idTasks) | ||
|
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 |
||
| r.Delete("/tasks/{id}", delTasks) | ||
|
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. deleteTask |
||
|
|
||
| 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.
PR теперь в репозиторий задания -нужно переделать
ранее было все ок
лучше чтобы весь процесс ревью по заданию был в одном PR
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.
Отправил ссылку на первый pr, там оба коммита и Ваши первые комментарии
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.
По названиям хэндлеров я понял, что надо более понятнее их давать. Когда отправлял ссылку затупил и не сделал третий коммит с названиями хэндлеров