mux.Vars 不工作

mux.Vars not working

我 运行 使用 HTTPS(端口 10443)并使用子路由:

mainRoute := mux.NewRouter()
mainRoute.StrictSlash(true)
mainRoute.Handle("/", http.RedirectHandler("/static/", 302))
mainRoute.PathPrefix("/static/").Handler(http.StripPrefix("/static", *fh))

// Bind API Routes
apiRoute := mainRoute.PathPrefix("/api").Subrouter()

apiProductRoute := apiRoute.PathPrefix("/products").Subrouter()
apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")

以及函数:

func listProducts(w http.ResponseWriter, r *http.Request) (interface{}, *handleHTTPError) {
    vars := mux.Vars(r)

    productType, ok := vars["id"]
    log.Println(productType)
    log.Println(ok)
}

okfalse,我不知道为什么。在 URL..

之后,我正在做一个简单的 ?type=model

当您输入 URL(例如 somedomain.com/products?type=model)时,您指定的是查询字符串,而不是变量。

Go 中的查询字符串通过 r.URL.Query 访问 - 例如

vals := r.URL.Query() // Returns a url.Values, which is a map[string][]string
productTypes, ok := vals["type"] // Note type, not ID. ID wasn't specified anywhere.
var pt string
if ok {
    if len(productTypes) >= 1 {
        pt = productTypes[0] // The first `?type=model`
    }
}

如您所见,这可能有点笨拙,因为它必须考虑到映射值为空以及 URL 像 somedomain.com/products?type=model&this=that&here=there&type=cat 可以指定键的可能性不止一次。

作为per the gorilla/mux docs你可以使用路由变量:

   // List all products, or the latest
   apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")
   // List a specific product
   apiProductRoute.Handle("/{id}/", handler(showProduct)).Methods("GET")

这是您要使用的地方 mux.Vars:

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

希望这有助于澄清。除非您特别需要使用查询字符串,否则我建议使用变量方法。

解决此问题的更简单方法是通过 Queries 在您的路由中添加查询参数,例如:

apiProductRoute.Handle("/", handler(listProducts)).
                Queries("type","{type}").Methods("GET")

您可以通过以下方式获取它:

v := mux.Vars(r)
type := v["type"]

注意:当问题最初发布时,这可能是不可能的,但是当我遇到类似问题并且大猩猩文档提供帮助时,我偶然发现了这个问题。