[笔记]gorolla/mux 的安装使用

学习自: 4.2. 集成 Gorilla Mux

安装

go get -u github.com/gorilla/mux

路由匹配规则

  • gorilla/mux: 精准匹配
  • net/http: 长度优先匹配

基本使用

http.HandleFunc(pattern, handler)

等价于

router := mux.NewRouter()
router.HandleFunc(pattern, handler)

支持的特性

  • 支持URI路径参数
  • 支持请求方法过滤
  • 支持路由命名

示例:

router.HandleFunc("/articles/{id:[0-9]+}", articlesShowHandler).Methods("GET").Name("articles.show")

注意: 在 Gorilla Mux 中,如未指定请求方法,默认会匹配所有方法。

获取URL路径参数的方式 mux.Vars

vars := mux.Vars(r)
id := vars["id"]

根据命名规则生成链接

artileURL,_ := router.Get('article.show').URL("id", "1024")
// => /articles/1024
今天你精进了吗?
讨论数量: 2

请问一下,为什么我执行了go get -u github.com/gorilla/mux之后报错呢

file

2年前 评论
aaron_19901 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!