URL 路径解析
goblog 中 URL 路径解析的代码如下:
http.HandleFunc("/", handlerFunc)
这段代码中反斜杠 /是指任意目录。
修改main.go代码,打印访问的url:
package mainimport ("fmt""net/http")func handlerFunc(w http.ResponseWriter, r *http.Request) {fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>")fmt.Fprint(w, "请求路径为:"+r.URL.Path)}func main() {http.HandleFunc("/", handlerFunc)http.ListenAndServe(":3000", nil)}
启动程序,浏览器访问以下三个链接,看看页面显示的结果:
再修改代码,根据访问的路径返回对应的内容:
package mainimport ("fmt""net/http")func handlerFunc(w http.ResponseWriter, r *http.Request) {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 {fmt.Fprint(w, "<h1>请求页面未找到 :(</h1>"+"<p>如有疑惑,请联系我们。</p>")}}func main() {http.HandleFunc("/", handlerFunc)http.ListenAndServe(":3000", nil)}
版本控制
本节我们新增了 about 页面,开始下节课之前我们先来做版本标记:
$ git add .$ git commit -m "新增关于页面"
自动重载
Go 语言为编译型语言,编译型语言有诸多好处,如:
- 部署简单
- 提早发现错误
- 执行效率高
然而这也意味着代码修改后需重新编译才能看到变更,这为我们本地开发带来了诸多不便。
安装 air 来实现自动编译:
$ go install github.com/cosmtrek/air@latest
安装成功后使用以下命令检查下:
$ air -v__ _ ___/ /\ | | | |_)/_/--\ |_| |_| \_ , built with Go
在我们的 goblog 项目根目录运行以下命令:
$ go mod tidy$ air
修改 main.go 文件,测试自动加载:
package mainimport ("fmt""net/http")func handlerFunc(w http.ResponseWriter, r *http.Request) {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 {fmt.Fprint(w, "<h1>请求页面未找到 :(</h1>"+"<p>如有疑惑,请联系我们。</p>")}}func main() {http.HandleFunc("/", handlerFunc)http.ListenAndServe(":3000", nil)}
浏览器访问 localhost:3000/ ,可以看到页面刷新了。
air在运行过程中会创建一个临时目录,在提交代码到git仓库时,可以忽略该文件。修改 .gitignore ,添加
tmp
设置header
package mainimport ("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 {fmt.Fprint(w, "<h1>请求页面未找到 :(</h1>"+"<p>如有疑惑,请联系我们。</p>")}}func main() {http.HandleFunc("/", handlerFunc)http.ListenAndServe(":3000", nil)}
设置404 状态码
package mainimport ("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)}
随便访问一个不存在的页面,然后查看请求返回的状态码。
