在带有 Gorilla Mux 的路径中间不能有路径参数吗?

时间:2021-01-31 02:52:48

标签: go 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
    ...

1 个答案:

答案 0 :(得分:0)

<块引用>

在带有 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]