参数路由,即接口请求路径并不是固定的,请求路径中的部分参数是请求参数,这在restful服务中非常常见,例如Java从Spring 3.0开始就提供了@PathVariable
这个注解实现这样一个参数路由的效果。
在Go中如果要实现这样的参数路由,需要安装外部包gorilla/mux,安装此包只需要执行以下命令即可:
go get -u github.com/gorilla/mux
安装可能会失败。如果提示:
go: golang.org/x/crypto@v0.0.0-20200622213623-75b288015ac9: Get “https://proxy.golang.org/golang.org/x/crypto/@v/v0.0.0-20200622213623-75b288015ac9.mod”: dial tcp 216.58.220.209:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
或者提示:
xxx
there is no tracking information for the current branch
xxx
出现这种问题基本都是由于网络问题导致的,反正命令行的包安装方式并不靠谱,这里推荐一种简单粗暴的安装方式,它既稳定又绝对靠谱:
- 直接下载对应的源码zip包,解压源码到
$GOPATH/src/
下并保持文件夹路径一致即可,本例中对应的文件夹路径为:$GOPATH/src/github.com/gorilla/mux
代码中引入github.com/gorilla/mux
,然后在HandleFunc
函数中通过{}
标识符即可实现接口路径参数化效果。以下是个完整的例子:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/books/{title}/page/{page}", func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
title := vars["title"]
page := vars["page"]
fmt.Fprintf(w, "You've requested the book: %s on page %s\n", title, page)
})
http.ListenAndServe(":8080", r)
}