goblog 学习二
今天学习了go module 和路由,引进社区的mux包。
路由
标准库自带http.ServeMux
,但有三个问题:
- 不支持URL路径参数
- 不支持请求方法的过滤,如果GET和POST
- 不支持路由的命名
教程选用Gorilla/mux作为路由器。实现精准匹配。用mux.Methods()区分请求方法;用Name()命名路由;
router.HandleFunc("/articles/{id:[0-9]+}", articlesShowHandler).Methods("GET").Name("articles.show")
中间件
引进中间件,解决重复度很高的代码:
w.Header().Set("Content-Type", "text/html; charset=utf-8")
实现的方式是,增加一个中间件的函数:
func forceHTMLMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 1. 设置标头
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// 2. 继续处理请求
h.ServeHTTP(w, r)
})
}
然后使用 Gorilla Mux 的 mux.Use() 方法,在main()中加载中间件:router.Use(forceHTMLMiddleware)
URL中的 “/” 问题
虽然mux可以用:
router := mux.NewRouter().StrictSlash(true)
解决ip:3000/about/
后面“/”问题(301跳转),但是没法ip:3000/
仍然会有错误。最后解决办法是增加一个预先处理请求的函数,用strings函数去掉末尾的“/”:
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)
})
}
用if语句做个判断。简单有效。
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: