diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..13566b8
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,8 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/.name b/.idea/.name
new file mode 100644
index 0000000..2a677c6
--- /dev/null
+++ b/.idea/.name
@@ -0,0 +1 @@
+precode.go
\ No newline at end of file
diff --git a/.idea/go-rest-api-homework.iml b/.idea/go-rest-api-homework.iml
new file mode 100644
index 0000000..5e764c4
--- /dev/null
+++ b/.idea/go-rest-api-homework.iml
@@ -0,0 +1,9 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..5002cd0
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..35eb1dd
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/precode.go b/precode.go
index d082d83..abdb43c 100644
--- a/precode.go
+++ b/precode.go
@@ -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{
@@ -28,7 +29,7 @@ var tasks = map[string]Task{
},
"2": {
ID: "2",
- Description: "Протестировать финальное задание с помощью Postmen",
+ Description: "Протестировать финальное задание с помощью Postman",
Note: "Лучше это делать в процессе разработки, каждый раз, когда запускаешь сервер и проверяешь хендлер",
Applications: []string{
"VS Code",
@@ -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 == "" {
+ http.Error(w, "ID задачи обязателен", http.StatusBadRequest)
+ return
+ }
+
+ 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())