forked from westonplatter/example-golang-todo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
188 lines (149 loc) · 4.74 KB
/
server.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"net/http"
"regexp"
)
// net/http based router
type route struct {
pattern *regexp.Regexp
verb string
handler http.Handler
}
type RegexpHandler struct {
routes []*route
}
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, verb string, handler http.Handler) {
h.routes = append(h.routes, &route{pattern, verb, handler})
}
func (h *RegexpHandler) HandleFunc(r string, v string, handler func(http.ResponseWriter, *http.Request)) {
re := regexp.MustCompile(r)
h.routes = append(h.routes, &route{re, v, http.HandlerFunc(handler)})
}
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, route := range h.routes {
if route.pattern.MatchString(r.URL.Path) && route.verb == r.Method {
route.handler.ServeHTTP(w, r)
return
}
}
http.NotFound(w, r)
}
// todo "Object"
type Todo struct {
Id int `json:"Id,sting"`
Title string `json:"Title"`
Category string `json:"Category"`
// Dt_created string `json:"Dt_created"`
// Dt_completed string `json:"Dt_completed"`
State string `json:"State"`
}
// store "context" values and connections in the server struct
type Server struct {
db *sql.DB
}
func main() {
db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/golang_todo_dev")
if err != nil {
log.Fatal(err)
}
db.SetMaxIdleConns(100)
defer db.Close()
server := &Server{db: db}
reHandler := new(RegexpHandler)
reHandler.HandleFunc("/todos/$", "GET", server.todoIndex)
reHandler.HandleFunc("/todos/$", "POST", server.todoCreate)
reHandler.HandleFunc("/todos/[0-9]+$", "GET", server.todoShow)
reHandler.HandleFunc("/todos/[0-9]+$", "PUT", server.todoUpdate)
reHandler.HandleFunc("/todos/[0-9]+$", "DELETE", server.todoDelete)
reHandler.HandleFunc(".*.[js|css|png|eof|svg|ttf|woff]", "GET", server.assets)
reHandler.HandleFunc("/", "GET", server.homepage)
fmt.Println("Starting server on port 3000")
http.ListenAndServe(":3000", reHandler)
}
// simple HTML/JS/CSS pages
func (s *Server) homepage(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res, req, "./index.html")
}
func (s *Server) assets(res http.ResponseWriter, req *http.Request) {
http.ServeFile(res, req, req.URL.Path[1:])
}
// Todo CRUD
func (s *Server) todoIndex(res http.ResponseWriter, req *http.Request) {
var todos []*Todo
rows, err := s.db.Query("SELECT Id, Title, Category, State FROM Todo")
error_check(res, err)
for rows.Next() {
todo := &Todo{}
rows.Scan(&todo.Id, &todo.Title, &todo.Category, &todo.State)
todos = append(todos, todo)
}
rows.Close()
jsonResponse(res, todos)
}
func (s *Server) todoCreate(res http.ResponseWriter, req *http.Request) {
todo := &Todo{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&todo)
if err != nil {
fmt.Println("ERROR decoding JSON - ", err)
return
}
defer req.Body.Close()
result, err := s.db.Exec("INSERT INTO Todo(Title, Category, State) VALUES(?, ?, ?)", todo.Title, todo.Category, todo.State)
if err != nil {
fmt.Println("ERROR saving to db - ", err)
}
Id64, err := result.LastInsertId()
Id := int(Id64)
todo = &Todo{Id: Id}
s.db.QueryRow("SELECT State, Title, Category FROM Todo WHERE Id=?", todo.Id).Scan(&todo.State, &todo.Title, &todo.Category)
jsonResponse(res, todo)
}
func (s *Server) todoShow(res http.ResponseWriter, req *http.Request) {
fmt.Println("Render todo json")
}
func (s *Server) todoUpdate(res http.ResponseWriter, req *http.Request) {
todoParams := &Todo{}
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&todoParams)
if err != nil {
fmt.Println("ERROR decoding JSON - ", err)
return
}
_, err = s.db.Exec("UPDATE Todo SET Title = ?, Category = ?, State = ? WHERE Id = ?", todoParams.Title, todoParams.Category, todoParams.State, todoParams.Id)
if err != nil {
fmt.Println("ERROR saving to db - ", err)
}
todo := &Todo{Id: todoParams.Id}
err = s.db.QueryRow("SELECT State, Title, Category FROM Todo WHERE Id=?", todo.Id).Scan(&todo.State, &todo.Title, &todo.Category)
if err != nil {
fmt.Println("ERROR reading from db - ", err)
}
jsonResponse(res, todo)
}
func (s *Server) todoDelete(res http.ResponseWriter, req *http.Request) {
r, _ := regexp.Compile(`\d+$`)
Id := r.FindString(req.URL.Path)
s.db.Exec("DELETE FROM Todo WHERE Id=?", Id)
res.WriteHeader(200)
}
func jsonResponse(res http.ResponseWriter, data interface{}) {
res.Header().Set("Content-Type", "application/json; charset=utf-8")
payload, err := json.Marshal(data)
if error_check(res, err) {
return
}
fmt.Fprintf(res, string(payload))
}
func error_check(res http.ResponseWriter, err error) bool {
if err != nil {
http.Error(res, err.Error(), http.StatusInternalServerError)
return true
}
return false
}