-
Notifications
You must be signed in to change notification settings - Fork 310
home_work_endpoints #211
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?
home_work_endpoints #211
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
| 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{ | ||
|
|
@@ -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 | ||
| } | ||
|
|
||
|
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. тут нужно проверить что такой задачи нет в 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()) | ||
|
|
||
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.
отлично что добавил эту проверку