mux.Vars不工作

时间:2015-07-12 18:26:30

标签: go gorilla

我在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,我不明白为什么。我在网址后面做了一个简单的?type=model ..

2 个答案:

答案 0 :(得分:26)

当您输入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`
    }
}

正如您所看到的,这可能有点笨拙,因为它必须考虑地图值为空,以及可能会像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"]

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

答案 1 :(得分:0)

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

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

你可以使用:

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

注意:这个问题最初发布时可能无法实现,但当我遇到类似问题并且大猩猩文档有所帮助时,我偶然发现了这一点。