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
83 changes: 82 additions & 1 deletion precode.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package main

import (
"bytes"
Copy link

Choose a reason for hiding this comment

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

image

PR теперь в репозиторий задания -нужно переделать

ранее было все ок

лучше чтобы весь процесс ревью по заданию был в одном PR

Copy link
Author

Choose a reason for hiding this comment

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

Отправил ссылку на первый pr, там оба коммита и Ваши первые комментарии

Copy link
Author

Choose a reason for hiding this comment

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

По названиям хэндлеров я понял, что надо более понятнее их давать. Когда отправлял ссылку затупил и не сделал третий коммит с названиями хэндлеров

"encoding/json"
"fmt"
"net/http"

Expand Down Expand Up @@ -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)
Copy link

Choose a reason for hiding this comment

The 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)
Copy link

Choose a reason for hiding this comment

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

getTasks

r.Post("/tasks", postTasks)
Copy link

Choose a reason for hiding this comment

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

addTask

r.Get("/tasks/{id}", idTasks)
Copy link

Choose a reason for hiding this comment

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

getTask

r.Delete("/tasks/{id}", delTasks)
Copy link

Choose a reason for hiding this comment

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