-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.go
79 lines (57 loc) · 1.16 KB
/
todo.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
package main
import (
"database/sql"
_ "github.com/lib/pq"
)
var db *sql.DB
func GetDB() *sql.DB {
if db != nil {
return db
} else {
db, err := sql.Open("postgres", "database=startit user=postgres sslmode=disable")
if err != nil {
panic(err)
}
return db
}
}
type Todo struct {
Id int `json:"id"`
Description string `json:"description"`
IsDone bool `json:"is_done"`
}
var TodoList []Todo
func GetTodo() Todo {
return Todo{1, "Gopeher meetup", false}
}
func AddTodo(newItem Todo) {
db := GetDB()
_, err := db.Exec("INSERT INTO todo(description,is_done) VALUES($1,$2)", newItem.Description, newItem.IsDone)
if err != nil {
panic(err)
}
}
func GetAll() []Todo {
db := GetDB()
var todoList []Todo
rows, err := db.Query("SELECT * FROM todo")
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var todo Todo
err := rows.Scan(&todo.Id, &todo.Description, &todo.IsDone)
if err != nil {
panic(err)
}
todoList = append(todoList, todo)
}
return todoList
}
func DeleteTodo(id int) {
db := GetDB()
if _, err := db.Exec("DELETE FROM todo WHERE id = $1", id); err != nil {
panic(err)
}
}