-
Notifications
You must be signed in to change notification settings - Fork 0
/
todo.go
89 lines (74 loc) · 2.04 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
80
81
82
83
84
85
86
87
88
89
/* todo app using Go. */
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/postgres"
)
var db *gorm.DB
var err error
func main() {
db, err = gorm.Open("postgres", os.Getenv("DATABASE_URL"))
if err != nil {
fmt.Println(err)
}
defer db.Close()
db.AutoMigrate(&todoModel{})
router := mux.NewRouter()
router.HandleFunc("/todos", getTodos).Methods("GET")
router.HandleFunc("/todos", createTodo).Methods("POST")
router.HandleFunc("/todos/{id}", getTodo).Methods("GET")
router.HandleFunc("/todos/{id}", updateTodo).Methods("PUT")
router.HandleFunc("/todos/{id}", deleteTodo).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8000", router))
}
type todoModel struct {
gorm.Model
Title string `json:"title"`
Completed bool `json:"completed"`
Due time.Time `json:"due"`
}
type todos []todoModel
func getTodos(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var todos []todoModel
db.Find(&todos)
json.NewEncoder(w).Encode(todos)
}
func createTodo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var todo todoModel
_ = json.NewDecoder(r.Body).Decode(&todo)
db.Create(&todo)
json.NewEncoder(w).Encode(todo)
}
func getTodo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
var todo todoModel
db.First(&todo, params["id"])
json.NewEncoder(w).Encode(todo)
}
func updateTodo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
var todo todoModel
db.First(&todo, params["id"])
_ = json.NewDecoder(r.Body).Decode(&todo)
db.Save(&todo)
json.NewEncoder(w).Encode(todo)
}
func deleteTodo(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
var todo todoModel
db.First(&todo, params["id"])
db.Delete(&todo)
json.NewEncoder(w).Encode(todo)
}