Skip to content
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

Four endpoints CCRD #197

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
72 changes: 67 additions & 5 deletions precode.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
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"`
Expand Down Expand Up @@ -39,14 +40,75 @@ var tasks = map[string]Task{
},
}

// Ниже напишите обработчики для каждого эндпоинта
// ...
func getTasks(w http.ResponseWriter, r *http.Request) {
resp, err := json.Marshal(tasks)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
}

func PostTask(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)
}

err = json.Unmarshal(buf.Bytes(), &task)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
tasks[task.ID] = task

w.WriteHeader(http.StatusCreated)

}

func GetTask(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
task, ok := tasks[id]
if !ok {
http.Error(w, "Task not found", http.StatusBadRequest)
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 DeleteTask(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")

_, ok := tasks[id]
if !ok {
http.Error(w, "Task not found", http.StatusBadRequest)
return
}

delete(tasks, id)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
}

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

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

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