是否不可能在带有 Gorilla Mux 的路径中间添加路径参数?

Sap*_*Sap 1 go mux gorilla

我有以下创建端点的 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))
    ... 
Run Code Online (Sandbox Code Playgroud)

下面是处理程序的片段。我像往常一样使用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
    ...
Run Code Online (Sandbox Code Playgroud)

mko*_*iva 6

是否不可能在带有 Gorilla Mux 的路径中间添加路径参数?

是的。

Mux 不支持路径中间的变量吗?

是的,它确实。

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)
}
Run Code Online (Sandbox Code Playgroud)
curl http://localhost:8000/device/123/job
Run Code Online (Sandbox Code Playgroud)

输出:

123
map[clusterID:123]
Run Code Online (Sandbox Code Playgroud)