mux.Vars不起作用

huangapple go评论84阅读模式
英文:

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))

// 绑定API路由
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)
}

ok 的值为 false,我不知道为什么。我在URL后面加了一个简单的 ?type=model

英文:

I'm running on HTTPS (port 10443) and use subroutes:

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")

And the functions:

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

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

ok is false and I have no idea why. I'm doing a simple ?type=model after my URL..

答案1

得分: 34

当你输入一个像somedomain.com/products?type=model这样的URL时,你指定的是一个查询字符串,而不是一个变量。

在Go语言中,可以通过r.URL.Query()来访问查询字符串,例如:

vals := r.URL.Query() // 返回一个url.Values,它是一个map[string][]string
productTypes, ok := vals["type"] // 注意是type,而不是ID。ID在任何地方都没有指定。
var pt string
if ok {
    if len(productTypes) >= 1 {
        pt = productTypes[0] // 第一个`?type=model`
    }
}

正如你所看到的,这可能有点笨拙,因为它必须考虑到映射值为空的情况,以及可能出现像somedomain.com/products?type=model&this=that&here=there&type=cat这样的URL,其中一个键可以被指定多次。

根据godoc.org/gorilla/mux的文档,你可以使用路由变量:

// 列出所有产品,或者最新的产品
apiProductRoute.Handle("/", handler(listProducts)).Methods("GET")
// 列出特定的产品
apiProductRoute.Handle("/{id}/", handler(showProduct)).Methods("GET")

这就是你可以使用mux.Vars的地方:

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

希望这能帮助澄清问题。我建议使用变量的方法,除非你特别需要使用查询字符串。

英文:

When you enter a URL like somedomain.com/products?type=model you're specifying a query string, not a variable.

Query strings in Go are accessed via r.URL.Query - e.g.

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`
    }
}

As you can see, this can be a little clunky as it has to account for the map value being empty and for the possibility of a URL like somedomain.com/products?type=model&this=that&here=there&type=cat where a key can be specified more than once.

As per the gorilla/mux docs you can use route variables:

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

This is where you would use mux.Vars:

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

Hope that helps clarify. I'd recommend the variables approach unless you specifically need to use query strings.

答案2

得分: 3

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

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

你可以使用以下代码获取查询参数:

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

注意:当最初提问时可能还没有这种解决方法,但当我遇到类似问题并查阅了gorilla文档后,我发现了这个方法。

英文:

An easier way to solve this is to add query parameters in your route through Queries, like:

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

You can get it using:

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

NOTE: This might not have been possible when the question was originally posted but I stumbled across this when I encountered a similar problem and the gorilla docs helped.

huangapple
  • 本文由 发表于 2015年7月13日 02:26:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/31371111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定