0

I'm using Gorilla mux for my handlers and using mux.Vars. I'm trying to write a test for one of the handlers that uses mux.Vars so what I do is

var vars = map[string]string{
    "id": user.ID,
}
context.Set(req, 0, vars)

In mux the key (an integer) is undefined so by default 0. I've logged the key when mux.Vars gets called and it prints 0. I should be able to key into this map

 map[0:map[id:522d14f5b1b92235d6000002]]

by doing map[key] but that returns nil. However, I get the correct value back if I hardcode map[0]. Any thoughts?

4

1 回答 1

0

我不完全确定我理解了这个问题,但看起来您可能会将 mux.Vars 与 mux.context 混淆。两者是独立的实体。前者返回从 URL 路径解析的路由变量。例如,您可以这样做:

r := mux.NewRouter()
r.HandleFunc("/blah/{foo}/", MyHandler)

...

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

后者包含您自己设置的上下文变量。例如:

func MyHandler(w http.ResponseWriter, r *http.Request) {
    context.Set(r, 0, map[string]string{"id": "myid"})
    myMap := context.Get(r, 0)
    ...
}

您可以查看一些其他人如何使用两者的用法示例,以了解最适合您的用例的内容:

mux.Vars:https ://sourcegraph.com/github.com/gorilla/mux/symbols/go/github.com/gorilla/mux/Vars mux.context : https ://sourcegraph.com/github.com/gorilla /context/symbols/go/github.com/gorilla/context

于 2013-09-12T00:18:52.463 回答