go 案例2 web项目搭建加数据库
2022年1月7日1. 使用自带模板引擎 html/template
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 |
package main import ( "fmt" "github.com/gorilla/mux" "html/template" "net/http" "net/url" "strings" "unicode/utf8" ) var router = mux.NewRouter() type ArticlesFormData struct { Title, Body string URL *url.URL Errors map[string]string } /** * 中间键方法 */ func forceHTMLMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") //1.设置标头 h.ServeHTTP(w, r) //2.继续处理请求 }) } 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:summer@example.com\">summer@example.com</a>") } func notFoundHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "<h1>请求页面未找到 :(</h1><p>如有疑惑,请联系我们。</p>") } func articlesShowHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] fmt.Fprint(w, "文章 ID:"+id) } func articlesIndexHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "访问文章列表") } func articlesStoreHandler(w http.ResponseWriter, r *http.Request) { title := r.PostFormValue("title") body := r.PostFormValue("body") 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 个字节" } // 检查是否有错误 if len(errors) == 0 { fmt.Fprint(w, "验证通过!<br>") fmt.Fprintf(w, "title 的值为: %v <br>", title) fmt.Fprintf(w, "title 的长度为: %v <br>", utf8.RuneCountInString(title)) fmt.Fprintf(w, "body 的值为: %v <br>", body) fmt.Fprintf(w, "body 的长度为: %v <br>", utf8.RuneCountInString(body)) } else { html := ` <!DOCTYPE html> <html lang="en"> <head> <title>创建文章 —— 我的技术博客</title> <style type="text/css">.error {color: red;}</style> </head> <body> <form action="{{ .URL }}" method="post"> <p><input type="text" name="title" value="{{ .Title }}"></p> {{ with .Errors.title }} <p class="error">{{ . }}</p> {{ end }} <p><textarea name="body" cols="30" rows="10">{{ .Body }}</textarea></p> {{ with .Errors.body }} <p class="error">{{ . }}</p> {{ end }} <p><button type="submit">提交</button></p> </form> </body> </html> ` storeURL, _ := router.Get("articles.store").URL() data := ArticlesFormData{ Title: title, Body: body, URL: storeURL, Errors: errors, } tmpl, err := template.New("create-form").Parse(html) if err != nil { panic(err) } err = tmpl.Execute(w, data) if err != nil { panic(err) } } } /** * 创建文章页面 */ func articlesCreateHandler(w http.ResponseWriter, r *http.Request) { html := ` <!DOCTYPE html> <html lang="en"> <head> <title>创建文章 —— 我的技术博客</title> </head> <body> <form action="%s?test=data" method="post"> <p><input type="text" name="title"></p> <p><textarea name="body" cols="30" rows="10"></textarea></p> <p><button type="submit">提交</button></p> </form> </body> </html> ` storeURL, _ := router.Get("articles.store").URL() //println(storeURL) fmt.Fprintf(w, html, storeURL) } /** * 移除路由后面斜杠的方法 */ func removeTrailingSlash(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //1. 除首页以外,移除所有请求路径后面的斜杆 if r.URL.Path != "/" { r.URL.Path = strings.TrimSuffix(r.URL.Path, "/") } //2. 将请求传递下去 next.ServeHTTP(w, r) }) } func main() { router.Use(forceHTMLMiddleware) router.HandleFunc("/", homeHandler).Methods("GET").Name("home") router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about") router.HandleFunc("/articles/create", articlesCreateHandler).Methods("GET").Name("articles.create") router.HandleFunc("/articles/{id:[0-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.NotFoundHandler = http.HandlerFunc(notFoundHandler) //自定义 404 页面 http.ListenAndServe(":3000", removeTrailingSlash(router)) } |
案例二
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 |
package main import ( "fmt" "github.com/gorilla/mux" "html/template" "net/http" "net/url" "strings" "unicode/utf8" ) var router = mux.NewRouter() type ArticlesFormData struct { Title, Body string URL *url.URL Errors map[string]string } /** * 中间键方法 */ func forceHTMLMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") //1.设置标头 h.ServeHTTP(w, r) //2.继续处理请求 }) } 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:summer@example.com\">summer@example.com</a>") } func notFoundHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "<h1>请求页面未找到 :(</h1><p>如有疑惑,请联系我们。</p>") } func articlesShowHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) id := vars["id"] fmt.Fprint(w, "文章 ID:"+id) } func articlesIndexHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "访问文章列表") } /** * 文章提交api */ func articlesStoreHandler(w http.ResponseWriter, r *http.Request) { title := r.PostFormValue("title") body := r.PostFormValue("body") 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 个字节" } if len(errors) > 0 { storeURL, _ := router.Get("articles.store").URL() data := ArticlesFormData{ Title: title, Body: body, URL: storeURL, Errors: errors, } tmpl, err := template.ParseFiles("resources/views/articles/create.gohtml") if err != nil { //如果读取模板有错 panic(err) } err = tmpl.Execute(w, data) if err != nil { //如果给模板赋值变量有错 panic(err) } return } fmt.Fprint(w, "验证通过!<br>") fmt.Fprintf(w, "title 的值为: %v <br>", title) fmt.Fprintf(w, "title 的长度为: %v <br>", utf8.RuneCountInString(title)) fmt.Fprintf(w, "body 的值为: %v <br>", body) fmt.Fprintf(w, "body 的长度为: %v <br>", utf8.RuneCountInString(body)) } /** * 创建文章页面 */ 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 removeTrailingSlash(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //1. 除首页以外,移除所有请求路径后面的斜杆 if r.URL.Path != "/" { r.URL.Path = strings.TrimSuffix(r.URL.Path, "/") } //2. 将请求传递下去 next.ServeHTTP(w, r) }) } func main() { router.Use(forceHTMLMiddleware) router.HandleFunc("/", homeHandler).Methods("GET").Name("home") router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about") router.HandleFunc("/articles/create", articlesCreateHandler).Methods("GET").Name("articles.create") router.HandleFunc("/articles/{id:[0-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.NotFoundHandler = http.HandlerFunc(notFoundHandler) //自定义 404 页面 http.ListenAndServe(":3000", removeTrailingSlash(router)) } |
3一个完整的增删改查
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 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 |
package main import ( "database/sql" "fmt" "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql" //匿名导入 "github.com/gorilla/mux" "log" "net/http" "net/url" "strconv" "strings" "text/template" "time" "unicode/utf8" ) var db *sql.DB //定义数据库链接 var router = mux.NewRouter() //定义路由 /** * 定义一个数据格式 */ type Article struct { Title, Body string ID int64 } /** * 定义一个数据格式 */ type ArticlesFormData struct { Title, Body string URL *url.URL Errors map[string]string } /** * RouteName2URL 通过路由名称来获取 URL */ func RouteName2URL(routeName string, pairs ...string) string { url, err := router.Get(routeName).URL(pairs...) if err != nil { checkError(err) return "" } return url.String() } /** * Int64ToString 将 int64 转换为 string */ func Int64ToString(num int64) string { return strconv.FormatInt(num, 10) } /** * Link 方法用来生成文章链接 */ 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() } /** * 添加删除方法 */ func (a Article) Delete() (rowsAffected int64, err error) { rs, err := db.Exec("DELETE FROM articles WHERE id = " + strconv.FormatInt(a.ID, 10)) if err != nil { return 0, err } // √ 删除成功,跳转到文章详情页 if n, _ := rs.RowsAffected(); n > 0 { return n, nil } return 0, nil } /** * 检查数据是有错的方法 */ func checkError(err error) { if err != nil { log.Fatal(err) return } } /** * 数据库链接的方法 */ func initDB() { var err error config := mysql.Config{ User: "root", Passwd: "123456", Addr: "127.0.0.1:3306", Net: "tcp", DBName: "goblog", AllowNativePasswords: true, } db, err = sql.Open("mysql", config.FormatDSN()) checkError(err) //准备数据库连接池 db.SetMaxOpenConns(25) //设置最大连接数 db.SetMaxIdleConns(25) //设置最大空闲连接数 db.SetConnMaxLifetime(5 * time.Minute) //设置每个链接的过期时间 err = db.Ping() checkError(err) //尝试连接,失败会报错 } /** * 创建表的方法 */ 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) } /** * DB 创建文章 */ func saveArticleToDB(title string, body string) (int64, error) { //变量初始化 var ( id int64 err error rs sql.Result stmt *sql.Stmt ) stmt, err = db.Prepare("INSERT INTO articles (title, body) VALUES(?,?)") //获取一个 prepare 声明语句 checkError(err) //检查错误 defer stmt.Close() //在此函数运行结束后关闭此语句,防止占用 SQL 连接 rs, err = stmt.Exec(title, body) //执行请求,传参进入绑定的内容 checkError(err) //检查所悟 //插入成功的话,会返回自增 ID if id, err = rs.LastInsertId(); id > 0 { return id, nil } return 0, err } /** * 数据验证 */ func validateArticleFormData(title string, 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 forceHTMLMiddleware(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") //1.设置标头 h.ServeHTTP(w, r) //2.继续处理请求 }) } /** * 404 页 */ func notFoundHandler(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "<h1>请求页面未找到 :(</h1><p>如有疑惑,请联系我们。</p>") } /** * 首页 */ 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:summer@example.com\">summer@example.com</a>") } /** * 文章首页 */ func articlesIndexHandler(w http.ResponseWriter, r *http.Request) { // 1. 执行查询语句,返回一个结果集 rows, err := db.Query("SELECT * from articles") checkError(err) defer rows.Close() var articles []Article //2. 循环读取结果 for rows.Next() { var article Article // 2.1 扫描每一行的结果并赋值到一个 article 对象中 err := rows.Scan(&article.ID, &article.Title, &article.Body) checkError(err) // 2.2 将 article 追加到 articles 的这个数组中 articles = append(articles, article) } // 2.3 检测遍历时是否发生错误 err = rows.Err() checkError(err) // 3. 加载模板 tmpl, err := template.ParseFiles("resources/views/articles/index.gohtml") checkError(err) // 4. 渲染模板,将所有文章的数据传输进去 err = tmpl.Execute(w, articles) checkError(err) } /** * 文章创建页面 */ 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") checkError(err) err = tmpl.Execute(w, data) checkError(err) } /** * 获取文章数据 */ func getArticleData(w http.ResponseWriter, r *http.Request) (Article, string, error) { //获取 URL 参数 vars := mux.Vars(r) id := vars["id"] //读取对应的文章数据 article := Article{} query := "SELECT * FROM articles WHERE id = ?" err := db.QueryRow(query, id).Scan(&article.ID, &article.Title, &article.Body) return article, id, err } /** * 文章详情页 */ func articlesShowHandler(w http.ResponseWriter, r *http.Request) { article, _, err := getArticleData(w, r) //如果出现错误 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 服务器内部错误") } return } //读取成功,显示文章 tmpl, err := template.New("show.gohtml").Funcs(template.FuncMap{ "RouteName2URL": RouteName2URL, "Int64ToString": Int64ToString, }).ParseFiles("resources/views/articles/show.gohtml") checkError(err) err = tmpl.Execute(w, article) checkError(err) } /** * 文章编辑页面 */ func articlesEditHandler(w http.ResponseWriter, r *http.Request) { article, id, err := getArticleData(w, r) // 3. 如果出现错误 if err != nil { if err == sql.ErrNoRows { // 3.1 数据未找到 w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "404 文章未找到") } else { // 3.2 数据库错误 checkError(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "500 服务器内部错误") } return } // 4. 读取成功,显示表单 updateURL, _ := router.Get("articles.update").URL("id", id) data := ArticlesFormData{ Title: article.Title, Body: article.Body, URL: updateURL, Errors: nil, } tmpl, err := template.ParseFiles("resources/views/articles/edit.gohtml") checkError(err) err = tmpl.Execute(w, data) checkError(err) } /** * 文章创建api */ func articlesStoreHandler(w http.ResponseWriter, r *http.Request) { title := r.PostFormValue("title") body := r.PostFormValue("body") errors := validateArticleFormData(title, body) if len(errors) > 0 { storeURL, _ := router.Get("articles.store").URL() data := ArticlesFormData{ Title: title, Body: body, URL: storeURL, Errors: errors, } tmpl, err := template.ParseFiles("resources/views/articles/create.gohtml") checkError(err) err = tmpl.Execute(w, data) checkError(err) return } lastInsertID, err := saveArticleToDB(title, body) if lastInsertID == 0 { checkError(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "500 服务器内部错误") return } indexURL, _ := router.Get("articles.index").URL() http.Redirect(w, r, indexURL.String(), http.StatusFound) } /** * 文章更新api */ func articlesUpdateHandler(w http.ResponseWriter, r *http.Request) { // 1. 获取 URL 参数 _, id, err := getArticleData(w, r) // 3. 如果出现错误 if err != nil { if err == sql.ErrNoRows { // 3.1 数据未找到 w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "404 文章未找到") } else { // 3.2 数据库错误 checkError(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "500 服务器内部错误") } return } // 4.1 表单验证 title := r.PostFormValue("title") body := r.PostFormValue("body") errors := validateArticleFormData(title, body) if len(errors) > 0 { // 4.3 表单验证不通过,显示理由 updateURL, _ := router.Get("articles.update").URL("id", id) data := ArticlesFormData{ Title: title, Body: body, URL: updateURL, Errors: errors, } tmpl, err := template.ParseFiles("resources/views/articles/edit.gohtml") checkError(err) err = tmpl.Execute(w, data) checkError(err) } // 4.2 表单验证通过,更新数据 query := "UPDATE articles SET title = ?, body = ? WHERE id = ?" rs, err := db.Exec(query, title, body, id) if err != nil { checkError(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "500 服务器内部错误") } // √ 更新成功,跳转到文章详情页 if n, _ := rs.RowsAffected(); n > 0 { showURL, _ := router.Get("articles.show").URL("id", id) http.Redirect(w, r, showURL.String(), http.StatusFound) } else { fmt.Fprint(w, "您没有做任何更改!") } } /** * 文章删除api */ func articlesDeleteHandler(w http.ResponseWriter, r *http.Request) { //1读取对应的文章数据 article, _, err := getArticleData(w, r) //2如果出现错误 if err != nil { if err == sql.ErrNoRows { // 3.1 数据未找到 w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "404 文章未找到") } else { // 3.2 数据库错误 checkError(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "500 服务器内部错误") } return } //3未出现错误,执行删除操作 rowsAffected, err := article.Delete() //4发生错误 if err != nil { // 应该是 SQL 报错了 checkError(err) w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, "500 服务器内部错误") return } //5未发生错误 if rowsAffected == 0 { // Edge case w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "404 文章未找到") } //6重定向到文章列表页 indexURL, _ := router.Get("articles.index").URL() http.Redirect(w, r, indexURL.String(), http.StatusFound) } /** * 移除路由后面斜杠的方法 */ func removeTrailingSlash(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //1. 除首页以外,移除所有请求路径后面的斜杆 if r.URL.Path != "/" { r.URL.Path = strings.TrimSuffix(r.URL.Path, "/") } //2. 将请求传递下去 next.ServeHTTP(w, r) }) } /** * 主方法写到里面就会调用执行 */ func main() { initDB() //初始化数据库 createTables() //创建表 router.Use(forceHTMLMiddleware) router.HandleFunc("/", homeHandler).Methods("GET").Name("home") router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about") router.HandleFunc("/articles/create", articlesCreateHandler).Methods("GET").Name("articles.create") router.HandleFunc("/articles/{id:[0-9]+}/edit", articlesEditHandler).Methods("GET").Name("articles.edit") router.HandleFunc("/articles/{id:[0-9]+}", articlesUpdateHandler).Methods("POST").Name("articles.update") router.HandleFunc("/articles/{id:[0-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/{id:[0-9]+}/delete", articlesDeleteHandler).Methods("POST").Name("articles.delete") router.NotFoundHandler = http.HandlerFunc(notFoundHandler) //自定义 404 页面 http.ListenAndServe(":3000", removeTrailingSlash(router)) } |