go 案例1 web小项目搭建
2022年1月7日代码1
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 |
package main /** * 引入包 */ import ( "fmt" "net/http" ) /** * 定义一个方法 */ func handlerFunc(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") //设置文件头和编码 if r.URL.Path == "/" { fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>") } else if r.URL.Path == "/about" { fmt.Fprint(w, "此博客是用以记录编程笔记,如您有反馈或建议,请联系 "+"<a href=\"mailto:summer@example.com\">summer@example.com</a>") } else { w.WriteHeader(http.StatusNotFound) //设置请求状态 fmt.Fprint(w, "<h1>请求页面未找到 :(</h1>"+"<p>如有疑惑,请联系我们。</p>") } } /** * 主方法自动运行 */ func main() { http.HandleFunc("/", handlerFunc) http.ListenAndServe(":3000", nil) } |
代码2重构
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 |
package main import ( "fmt" "net/http" ) /** * 首页方法 */ func defaultHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if r.URL.Path == "/" { fmt.Fprint(w, "<h1>Hello, 欢迎来到 goblog!</h1>") } else { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "<h1>请求页面未找到 :(</h1>"+ "<p>如有疑惑,请联系我们。</p>") } } /** * 详情页方法 */ func aboutHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprint(w, "此博客是用以记录编程笔记,如您有反馈或建议,请联系 "+ "<a href=\"mailto:summer@example.com\">summer@example.com</a>") } /** * 主要运行程序 */ func main() { http.HandleFunc("/", defaultHandler) http.HandleFunc("/about", aboutHandler) http.ListenAndServe(":3000", nil) } |
代码3 加入http.NewServeMux 路由 重构
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 |
package main import ( "fmt" "net/http" "strings" ) /** * 首页方法 */ func defaultHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if r.URL.Path == "/" { fmt.Fprint(w, "<h1>Hello, 欢迎来到 goblog!</h1>") } else { w.WriteHeader(http.StatusNotFound) fmt.Fprint(w, "<h1>请求页面未找到 :(</h1>"+ "<p>如有疑惑,请联系我们。</p>") } } /** * 关于我们的方法 */ func aboutHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprint(w, "此博客是用以记录编程笔记,如您有反馈或建议,请联系 "+ "<a href=\"mailto:summer@example.com\">summer@example.com</a>") } /** * 文章详情页方法 * 冒号加等于号 是肤质 := * 数组计数是从1开始 */ func articlesHandler(w http.ResponseWriter, r *http.Request) { id := strings.SplitN(r.URL.Path, "/", 3)[2] switch r.Method { case "GET": fmt.Fprint(w, "访问文章列表"+id) case "POST": fmt.Fprint(w, "创建新的文章"+id) } } /** * 主要运行程序 */ func main() { router := http.NewServeMux() router.HandleFunc("/", defaultHandler) router.HandleFunc("/about", aboutHandler) router.HandleFunc("/articles/", articlesHandler) http.ListenAndServe(":3000", router) } |
代码4 使用mux 路由
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 |
package main import ( "fmt" "github.com/gorilla/mux" "net/http" ) func homeHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprint(w, "<h1>Hello, 欢迎来到 goblog!</h1>") } func aboutHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") fmt.Fprint(w, "此博客是用以记录编程笔记,如您有反馈或建议,请联系 <a href=\"mailto:summer@example.com\">summer@example.com</a>") } func notFoundHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") 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) { fmt.Fprint(w, "创建新的文章") } func main() { router := mux.NewRouter().StrictSlash(true) router.HandleFunc("/", homeHandler).Methods("GET").Name("home") router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about") 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 页面 /** * 通过别名获取 URL 示例 */ homeURL, _ := router.Get("home").URL() articleURL, _ := router.Get("articles.show").URL("id", "23") fmt.Println("homeURL: ", homeURL) fmt.Println("articleURL: ", articleURL) http.ListenAndServe(":3000", router) } |
代码5 添加中间件
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 |
package main import ( "fmt" "github.com/gorilla/mux" "net/http" ) /** * 中间键方法 */ 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) { fmt.Fprint(w, "创建新的文章") } func main() { router := mux.NewRouter().StrictSlash(true) router.Use(forceHTMLMiddleware) router.HandleFunc("/", homeHandler).Methods("GET").Name("home") router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about") 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", router) } |
代码5 post
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 |
package main import ( "fmt" "github.com/gorilla/mux" "net/http" "strings" ) var router = mux.NewRouter() /** * 中间键方法 */ 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) { err := r.ParseForm() if err != nil { fmt.Fprint(w, "请提供正确的数据!") // 解析错误,这里应该有错误处理 return } title := r.PostForm.Get("title") fmt.Fprintf(w, "POST PostForm: %v <br>", r.PostForm) fmt.Fprintf(w, "POST Form: %v <br>", r.Form) fmt.Fprintf(w, "title 的值为: %v", title) } 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)) } |
数据接收