-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
129 lines (88 loc) · 2.37 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"encoding/json"
"fmt"
"igabir98/simpleTODO/engine"
"igabir98/simpleTODO/models"
"net/http"
"github.com/asaskevich/govalidator"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
type App struct {
db *engine.BoltDB
}
var app App
func main() {
db, err := engine.NewBoltDB()
if err != nil {
fmt.Println(err)
}
app.db = db
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Get("/", welcome)
r.Get("/tasks", getAll)
r.Get("/tasks/{taskID}", getTask)
r.Post("/tasks", create)
r.Put("/tasks", update)
r.Delete("/tasks/{taskID}", deleteTask)
http.ListenAndServe(":3000", r)
}
func welcome(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("welcome"))
}
func create(w http.ResponseWriter, req *http.Request) {
var task models.Task
json.NewDecoder(req.Body).Decode(&task)
w.Header().Set("Content-Type", "application/json")
_, err := app.db.CreateTask(&task)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(task)
}
func update(w http.ResponseWriter, req *http.Request) {
var task models.Task
json.NewDecoder(req.Body).Decode(&task)
_, err := app.db.UpdateTask(&task)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(task)
}
func getAll(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusFound)
tasks, _ := app.db.GetAllTasks()
json.NewEncoder(w).Encode(tasks)
}
func getTask(w http.ResponseWriter, req *http.Request) {
taskID := chi.URLParam(req, "taskID")
w.Header().Set("Content-Type", "application/json")
tasks, err := app.db.GetTask(taskID)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusFound)
json.NewEncoder(w).Encode(tasks)
}
func deleteTask(w http.ResponseWriter, req *http.Request) {
taskID := chi.URLParam(req, "taskID")
w.Header().Set("Content-Type", "application/json")
err := app.db.DeleteTask(taskID)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
func init() {
govalidator.SetFieldsRequiredByDefault(true)
}