-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
389 lines (369 loc) · 10.9 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
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
"strings"
"text/template"
"unicode/utf8"
"github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
)
var db *sql.DB
var router = mux.NewRouter()
type Article struct {
ID int64
Title, Body string
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "<h1>hello, 欢迎来到goblog项目!</h1>")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "此博客用以记录编程笔记,如有反馈或建议,请联系"+
"<a href=\"mailto:[email protected]\">[email protected]</a>")
}
func articlesShowHandler(w http.ResponseWriter, r *http.Request) {
id := getRouteVariable("id", r)
//fmt.Fprint(w, "文章id:"+id)
article, err := getArticleByID(id)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 文章未找到")
} else {
checkError(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
}
} else {
//fmt.Fprint(w, "读取成功,标题为:"+article.Title)
//templ, err := template.ParseFiles("./resources/views/articles/show.gohtml")
templ, err := template.New("show.gohtml").Funcs(template.FuncMap{
"Int64ToString": Int64ToString,
"RouteName2URL": RouteName2URL,
}).ParseFiles("./resources/views/articles/show.gohtml")
checkError(err)
err = templ.Execute(w, article)
checkError(err)
}
}
func Int64ToString(num int64) string {
return strconv.FormatInt(num, 10)
}
func RouteName2URL(routeName string, pairs ...string) string {
url, err := router.Get(routeName).URL(pairs...)
if err != nil {
checkError(err)
return ""
} else {
return url.String()
}
}
func articlesIndexHandler(w http.ResponseWriter, r *http.Request) {
///fmt.Fprint(w, "访问文章列表")
rows, err := db.Query("SELECT * from articles;")
checkError(err)
defer rows.Close()
var articles []Article
for rows.Next() {
var article Article
err = rows.Scan(&article.ID, &article.Title, &article.Body)
checkError(err)
articles = append(articles, article)
}
err = rows.Err()
checkError(err)
templ, err := template.ParseFiles("resources/views/articles/index.gohtml")
checkError(err)
err = templ.Execute(w, articles)
checkError(err)
}
func (a Article) Link() string {
showURL, err := router.Get("articles.show").URL("id", strconv.FormatInt(a.ID, 10))
if err != nil {
checkError(err)
return ""
}
return showURL.String()
}
type ArticlesFormData struct {
Title, Body string
URL *url.URL
Errors map[string]string
}
func articlesCreateHandler(w http.ResponseWriter, r *http.Request) {
storeURL, _ := router.Get("articles.store").URL()
data := ArticlesFormData{
Title: "",
Body: "",
URL: storeURL,
Errors: nil,
}
tmpl, err := template.ParseFiles("resources/views/articles/create.gohtml")
if err != nil {
panic(err)
}
err = tmpl.Execute(w, data)
if err != nil {
panic(err)
}
}
func articlesStoreHandler(w http.ResponseWriter, r *http.Request) {
title := r.PostFormValue("title")
body := r.PostFormValue("body")
errors := validateArticleFormData(title, body)
if len(errors) == 0 {
fmt.Fprint(w, "验证通过!")
lastInsertID, err := saveArticleToDB(title, body)
if lastInsertID > 0 {
fmt.Fprint(w, "插入成功,ID为"+strconv.FormatInt(lastInsertID, 10))
} else {
checkError(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
}
} else {
fmt.Fprintf(w, "验证失败,errors: %v <br>", errors)
}
storeURL, _ := router.Get("articles.store").URL()
data := ArticlesFormData{
Title: title,
Body: body,
URL: storeURL,
Errors: errors,
}
//tmpl, err := template.New("create-form").Parse(html)
tmpl, err := template.ParseFiles("resources/views/articles/create.gohtml")
if err != nil {
panic(err)
}
err = tmpl.Execute(w, data)
if err != nil {
panic(err)
}
}
func saveArticleToDB(title, body string) (int64, error) {
var (
err error
id int64
result sql.Result
stmt *sql.Stmt
)
stmt, err = db.Prepare("INSERT INTO articles (title, body) VALUES(?, ?)")
if err != nil {
return 0, err
}
defer stmt.Close()
result, err = stmt.Exec(title, body)
if err != nil {
return 0, err
}
if id, err = result.LastInsertId(); id > 0 {
return id, nil
}
return 0, err
}
func articlesEditHandler(w http.ResponseWriter, r *http.Request) {
id := getRouteVariable("id", r)
//fmt.Fprint(w, "文章id:"+id)
article, err := getArticleByID(id)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 文章未找到")
} else {
checkError(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
}
} else {
//fmt.Fprint(w, "读取成功,标题为:"+article.Title)
url, _ := router.Get("articles.update").URL("id", id)
data := ArticlesFormData{
Title: article.Title,
Body: article.Body,
URL: url,
Errors: nil,
}
templ, err := template.ParseFiles("./resources/views/articles/edit.gohtml")
checkError(err)
err = templ.Execute(w, data)
checkError(err)
}
}
func articlesUpdateHandler(w http.ResponseWriter, r *http.Request) {
id := getRouteVariable("id", r)
//fmt.Fprint(w, "文章id:"+id)
_, err := getArticleByID(id)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 文章未找到")
} else {
checkError(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
}
} else {
//fmt.Fprint(w, "读取成功,标题为:"+article.Title)
title := r.PostFormValue("title")
body := r.PostFormValue("body")
errors := validateArticleFormData(title, body)
if len(errors) == 0 {
query := `UPDATE articles SET title=?, body=? WHERE id=?`
result, err := db.Exec(query, title, body, id)
if err != nil {
checkError(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
}
if n, _ := result.RowsAffected(); n > 0 {
showUrl, _ := router.Get("articles.show").URL("id", id)
http.Redirect(w, r, showUrl.String(), http.StatusFound)
} else {
fmt.Fprint(w, "您没有做任何改变!")
}
} else {
fmt.Fprintf(w, "验证失败,errors: %v <br>", errors)
storeURL, _ := router.Get("articles.update").URL("id", id)
data := ArticlesFormData{
Title: title,
Body: body,
URL: storeURL,
Errors: errors,
}
//tmpl, err := template.New("create-form").Parse(html)
tmpl, err := template.ParseFiles("resources/views/articles/edit.gohtml")
checkError(err)
err = tmpl.Execute(w, data)
checkError(err)
}
}
}
func articlesDeleteHandler(w http.ResponseWriter, r *http.Request) {
id := getRouteVariable("id", r)
article, err := getArticleByID(id)
if err != nil {
if err == sql.ErrNoRows {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 文章未找到")
} else {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
}
} else {
rowsAffected, err := article.Delete()
if err != nil {
checkError(err)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "500 服务器内部错误")
} else {
if rowsAffected > 0 {
indexURL, _ := router.Get("articles.index").URL()
http.Redirect(w, r, indexURL.String(), http.StatusFound)
} else {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 文章未找到")
}
}
}
}
func (a Article) Delete() (int64, error) {
result, err := db.Exec("DELETE FROM articles where id = " + strconv.FormatInt(a.ID, 10))
if err != nil {
return 0, err
}
if n, _ := result.RowsAffected(); n > 0 {
return n, nil
}
return 0, nil
}
func getRouteVariable(parameterName string, r *http.Request) string {
values := mux.Vars(r)
value := values[parameterName]
return value
}
func getArticleByID(id string) (Article, error) {
article := Article{}
query := `SELECT * FROM articles WHERE id = ?`
err := db.QueryRow(query, id).Scan(&article.ID, &article.Title, &article.Body)
return article, err
}
func validateArticleFormData(title, body string) map[string]string {
errors := make(map[string]string)
if title == "" {
errors["title"] = "标题不能为空"
} else if utf8.RuneCountInString(title) < 3 || utf8.RuneCountInString(title) > 40 {
errors["title"] = "标题长度需介于3-40"
}
if body == "" {
errors["body"] = "内容不能为空"
} else if utf8.RuneCountInString(body) < 10 {
errors["body"] = "内容不能少于10个字节"
}
return errors
}
func notFoundHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "<h1>请求页未找到 :(</h1>"+"<p>如有疑惑,请联系我们。</p>")
}
func forceHTMLMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
next.ServeHTTP(w, r)
})
}
func removeTrailingSlash(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.TrimSuffix(r.URL.Path, "/")
next.ServeHTTP(w, r)
})
}
func initDB() {
var err error
config := mysql.Config{
User: "root",
Passwd: "Kylin*2020",
Net: "tcp",
Addr: "127.0.0.1",
DBName: "goblog",
AllowNativePasswords: true,
}
db, err = sql.Open("mysql", config.FormatDSN())
checkError(err)
err = db.Ping()
checkError(err)
}
func checkError(err error) {
if err != nil {
log.Fatal()
}
}
func createTables() {
createArticlesSQL := `CREATE TABLE IF NOT EXISTS articles(
id bigint(20) PRIMARY KEY AUTO_INCREMENT NOT NULL,
title varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
body longtext COLLATE utf8mb4_unicode_ci
);`
_, err := db.Exec(createArticlesSQL)
checkError(err)
}
func main() {
initDB()
createTables()
router.HandleFunc("/home", homeHandler).Methods("GET").Name("home")
router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about")
router.HandleFunc("/articles/{id:[1-9]+}", articlesShowHandler).Methods("GET").Name("articles.show")
router.HandleFunc("/articles", articlesIndexHandler).Methods("GET").Name("articles.index")
router.HandleFunc("/articles", articlesStoreHandler).Methods("POST").Name("articles.store")
router.HandleFunc("/articles/create", articlesCreateHandler).Methods("GET").Name("articles.create")
router.HandleFunc("/articles/{id:[1-9]+}/edit", articlesEditHandler).Methods("GET").Name("articles.edit")
router.HandleFunc("/articles/{id:[1-9]+}", articlesUpdateHandler).Methods("POST").Name("articles.update")
router.HandleFunc("/articles/{id:[1-9]+}/delete", articlesDeleteHandler).Methods("POST").Name("articles.delete")
router.NotFoundHandler = http.HandlerFunc(notFoundHandler)
router.Use(forceHTMLMiddleware)
http.ListenAndServe("127.0.0.1:3000", removeTrailingSlash(router))
}