Skip to content
Open
Show file tree
Hide file tree
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
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions .idea/.name

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions .idea/go-rest-api-homework.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

96 changes: 86 additions & 10 deletions precode.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
package main

import (
"bytes"
"encoding/json"
"fmt"
"net/http"

"github.com/go-chi/chi/v5"
)

// Task ...
type Task struct {
ID string `json:"id"`
Description string `json:"description"`
Note string `json:"note"`
Applications []string `json:"applications"`
ID string `json:"id"` // ID задачи
Description string `json:"description"` // Заголовок
Note string `json:"note"` // Описание задачи
Applications []string `json:"applications"` // Приложения, которыми будете пользоваться
}

var tasks = map[string]Task{
Expand All @@ -28,7 +29,7 @@ var tasks = map[string]Task{
},
"2": {
ID: "2",
Description: "Протестировать финальное задание с помощью Postmen",
Description: "Протестировать финальное задание с помощью Postman",
Note: "Лучше это делать в процессе разработки, каждый раз, когда запускаешь сервер и проверяешь хендлер",
Applications: []string{
"VS Code",
Expand All @@ -39,14 +40,89 @@ var tasks = map[string]Task{
},
}

// Ниже напишите обработчики для каждого эндпоинта
// ...
func getAllTasks(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

resp, err := json.Marshal(tasks)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

w.WriteHeader(http.StatusOK)
_, _ = w.Write(resp)
}

func getTaskByID(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")

task, ok := tasks[id]
if !ok {
http.Error(w, "Задача не найдена", http.StatusNoContent) // 204 No Content
return
}

resp, err := json.Marshal(task)
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 createTask(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.StatusBadRequest)
return
}

if err = json.Unmarshal(buf.Bytes(), &task); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

if task.ID == "" {

Choose a reason for hiding this comment

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

отлично что добавил эту проверку

http.Error(w, "ID задачи обязателен", http.StatusBadRequest)
return
}

Choose a reason for hiding this comment

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

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

if _, exists := tasks[task.ID]; exists {
http.Error(w, "Задача с таким ID уже существует", http.StatusConflict) // 409 Conflict
return
}

tasks[task.ID] = task

w.WriteHeader(http.StatusCreated) // 201 Created
}

func deleteTaskByID(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")

if _, exists := tasks[id]; !exists {
http.Error(w, "Задача не найдена", http.StatusBadRequest)
return
}

delete(tasks, id)

w.WriteHeader(http.StatusOK) // 200 OK
}

func main() {
r := chi.NewRouter()

// здесь регистрируйте ваши обработчики
// ...
r.Get("/tasks", getAllTasks)
r.Get("/tasks/{id}", getTaskByID)
r.Post("/tasks", createTask)
r.Delete("/tasks/{id}", deleteTaskByID)

if err := http.ListenAndServe(":8080", r); err != nil {
fmt.Printf("Ошибка при запуске сервера: %s", err.Error())
Expand Down