英文:
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("id")
req.Form.Get("1")
req.Form.Get("_1")
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("/api/users/{userId}/categories/{categoryId}/posts/{postId}",
MyHandler)
And then in your handler you can access them:
vars := mux.Vars(request)
userId := vars["userId"]
// etc...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论