Golang:获取未命名参数

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

Golang: get not named params

问题

例如,我有一个请求:

POST /api/users/1/categories/2/posts/3

我如何访问这些参数?

我尝试过:

req.ParseMultipartForm(defaultMaxMemory)

req.Form.Get("id")
req.Form.Get("1")
req.Form.Get("_1")

但是它不起作用。

关于GET请求的同样问题:

GET /api/users/1/categories/2/posts/3

如何获取未命名的参数?

req.URL.Query().Get(???)
英文:

For example, I have a request:

POST /api/users/1/categories/2/posts/3

How can I access this params?
<br>
<br>
I've tried:

req.ParseMultipartForm(defaultMaxMemory)

req.Form.Get(&quot;id&quot;)
req.Form.Get(&quot;1&quot;)
req.Form.Get(&quot;_1&quot;)

But it doesn't work.
<br>
<br>
Same question about GET:

GET /api/users/1/categories/2/posts/3

How to get not named params?
<br>

req.URL.Query().Get(???)

答案1

得分: 6

如果你正在使用默认的HTTP服务器库,你需要解析URL路径部分并提取它们。

有一些库,比如Gorilla Mux(我个人喜欢),可以自动添加这个逻辑。http://www.gorillatoolkit.org/pkg/mux

使用Gorilla/mux,当你注册处理程序时,可以这样注册:

r := mux.NewRouter()
r.HandleFunc("/api/users/{userId}/categories/{categoryId}/posts/{postId}", 
             MyHandler)

然后在你的处理程序中可以访问它们:

vars := mux.Vars(request)
userId := vars["userId"]
// 等等...
英文:

If you are using the default http server library, you'll need to parse the Url path parts and extract them.

There are libraries like Gorilla Mux (which I personally like) that you can use to add this logic automatically. http://www.gorillatoolkit.org/pkg/mux

Using Gorilla/mux, when you register your handler, you register it like so:

r := mux.NewRouter()
r.HandleFunc(&quot;/api/users/{userId}/categories/{categoryId}/posts/{postId}&quot;, 
             MyHandler)

And then in your handler you can access them:

vars := mux.Vars(request)
userId := vars[&quot;userId&quot;]
// etc...

huangapple
  • 本文由 发表于 2014年10月30日 17:07:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/26648881.html
匿名

发表评论

匿名网友

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

确定