如何解决在带有 Gorilla Mux 的路径中间不能有路径参数吗?
我有以下创建端点的 API 服务器片段,我想将“clusterID”抽象为处理程序中的路径参数。这是路由器部分
func main() {
router := mux.NewRouter().StrictSlash(true)
sub := router.PathPrefix("/api/v1").Subrouter()
sub.Methods("GET").Path("/device/{clusterID}/job").HandlerFunc(authDev(getJob))
...
以下是处理程序的片段。我像往常一样使用 mux.Vars()
获取变量。如果我向 localshost/api/v1/device/cluster123/job
发送请求,处理程序会按预期调用,但 mux.Vars(r)
返回一个空地图,而不是按预期返回带有 clusterID=cluster123
的地图。 Mux 不支持路径中间的变量吗?我知道我可以手动解析路径,但我希望 Mux 为我做这件事。
func getJob(w http.ResponseWriter,r *http.Request) {
params := mux.Vars(r)
log.Println(params["clusterID"]) // outputs an empty string
log.Println(params) // outputs an empty map
...
解决方法
在带有 Gorilla Mux 的路径中间不能有路径参数吗?
是的,是的。
Mux 不支持路径中间的 vars 吗?
是的,确实如此。
package main
import (
"fmt"
"github.com/gorilla/mux"
"net/http"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/device/{clusterID}/job",getJob)
http.ListenAndServe(":8000",r)
}
func getJob(w http.ResponseWriter,r *http.Request) {
params := mux.Vars(r)
fmt.Println(params["clusterID"])
fmt.Println(params)
}
curl http://localhost:8000/device/123/job
输出:
123
map[clusterID:123]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。