-
Notifications
You must be signed in to change notification settings - Fork 0
/
todolist.go
137 lines (118 loc) · 3.94 KB
/
todolist.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
130
131
132
133
134
135
136
137
package main
import (
"encoding/json"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"github.com/rs/cors"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"strconv"
)
var db, _ = gorm.Open("mysql", "user:pass@/todolist?charset=utf8&parseTime=True&loc=Local")
type TodoItemModel struct {
Id int `gorm:"primary_key"`
Description string
Completed bool
}
func CreateItem(w http.ResponseWriter, r *http.Request) {
description := r.FormValue("description")
log.WithFields(log.Fields{"description": description}).Info("Add new TodoItem. Saving to database.")
todo := &TodoItemModel{Description: description, Completed: false}
db.Create(&todo)
result := db.Last(&todo).Value
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(result)
}
func UpdateItem(w http.ResponseWriter, r *http.Request) {
// Get URL parameter from mux
vars := mux.Vars(r)
id, _ := strconv.Atoi(vars["id"])
// Test if the TodoItem exist in DB
err := GetItemByID(id)
if err == false {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"updated": false, "error": "Record Not Found"}`)
} else {
completed, _ := strconv.ParseBool(r.FormValue("completed"))
log.WithFields(log.Fields{"Id": id, "Completed": completed}).Info("Updating TodoItem")
todo := &TodoItemModel{}
db.First(&todo, id)
todo.Completed = completed
db.Save(&todo)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"updated": true}`)
}
}
func DeleteItem(w http.ResponseWriter, r *http.Request) {
// Get URL parameter from mux
vars := mux.Vars(r)
id, _ := strconv.Atoi(vars["id"])
// Test if the TodoItem exist in DB
err := GetItemByID(id)
if err == false {
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"deleted": false, "error": "Record Not Found"}`)
} else {
log.WithFields(log.Fields{"Id": id}).Info("Deleting TodoItem")
todo := &TodoItemModel{}
db.First(&todo, id)
db.Delete(&todo)
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"deleted": true}`)
}
}
func GetItemByID(Id int) bool {
todo := &TodoItemModel{}
result := db.First(&todo, Id)
if result.Error != nil {
log.Warn("TodoItem not found in database")
return false
}
return true
}
func GetCompletedItems(w http.ResponseWriter, r *http.Request) {
log.Info("Get completed TodoItems")
completedTodoItems := GetTodoItems(true)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(completedTodoItems)
}
func GetIncompleteItems(w http.ResponseWriter, r *http.Request) {
log.Info("Get Incomplete TodoItems")
IncompleteTodoItems := GetTodoItems(false)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(IncompleteTodoItems)
}
func GetTodoItems(completed bool) interface{} {
var todos []TodoItemModel
TodoItems := db.Where("completed = ?", completed).Find(&todos).Value
return TodoItems
}
func Healthz(w http.ResponseWriter, r *http.Request) {
log.Info("API Health is OK")
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"alive": true}`)
}
func init() {
log.SetFormatter(&log.TextFormatter{})
log.SetReportCaller(true)
}
func main() {
defer db.Close()
db.Debug().DropTableIfExists(&TodoItemModel{})
db.Debug().AutoMigrate(&TodoItemModel{})
log.Info("Starting Todolist API server")
router := mux.NewRouter()
router.HandleFunc("/healthz", Healthz).Methods("GET")
router.HandleFunc("/todo-completed", GetCompletedItems).Methods("GET")
router.HandleFunc("/todo-incomplete", GetIncompleteItems).Methods("GET")
router.HandleFunc("/todo", CreateItem).Methods("POST")
router.HandleFunc("/todo/{id}", UpdateItem).Methods("POST")
router.HandleFunc("/todo/{id}", DeleteItem).Methods("DELETE")
handler := cors.New(cors.Options{
AllowedMethods: []string{"GET", "POST", "DELETE", "PATCH", "OPTIONS"},
}).Handler(router)
http.ListenAndServe(":8000", handler)
}