英文:
Gorilla Mux to handle curl request
问题
我想使用Gorilla mux来处理API请求。
命令的格式应该是这样的:
curl http://0.0.0.0:8000/api/myapiname/v1?number=10&target=google.com&message=hello
我正在使用以下处理程序进行服务:
router.Methods("GET").Path("/api/myapiname/{version}").HandlerFunc(apihandler)
func apihandler(rw http.ResponseWriter, q *http.Request) {
vars := mux.Vars(q)
log.Println(vars["version"])
log.Println(q.FormValue("number"))
log.Println(q.FormValue("target"))
log.Println(q.FormValue("message"))
}
但是对于curl
请求,我只能获取到number
的表单值,而无法获取到target
和message
的值。
使用Gorilla mux处理API请求的正确方法是什么?我需要使用子路由吗?
我只想接收形如http://0.0.0.0:8000/api/myapiname/v1?number=10&target=google.com&message=hello
的任何HTTP请求,并能够将其键映射到值。
谢谢!
英文:
I want to use Gorilla mux to handle api requests.
Commands will be something like:
curl http://0.0.0.0:8000/api/myapiname/v1?number=10&target=google.com&message=hello
And I am serving with following handlers:
router.Methods("GET").Path("/api/myapiname/{version}").HandlerFunc(apihandler)
func apihandler(rw http.ResponseWriter, q *http.Request) {
vars := mux.Vars(q)
log.Println(vars["version"])
log.Println(q.FormValue("number"))
log.Println(q.FormValue("target"))
log.Println(q.FormValue("message"))
}
But for the curl
requests I only get the form value of number
not target
and message
's
What is the correct way of handle api requests using Gorilla mux? Do I need sub routing?
I just want to receive any http request of form http://0.0.0.0:8000/api/myapiname/v1?number=10&target=google.com&message=hello
and be able to map its key to value
THanks!
答案1
得分: 1
你可以尝试将查询添加到你的路由器中,这样你就可以在一个映射中获取所有的变量。
router.Methods("GET").Path("/api/myapiname/{version}").Queries("number", "{number:[0-9]+}", "target", "{target:[^&]+}", "message", "{message:[^&]+}").HandlerFunc(apihandler)
func apihandler(rw http.ResponseWriter, q *http.Request) {
vars := mux.Vars(q)
log.Println(vars["version"])
log.Println(vars["number"])
log.Println(vars["target"])
log.Println(vars["message"])
}
英文:
You may try to add Queries to your router, in that case you will have all vars in one map.
router.Methods("GET").Path("/api/myapiname/{version}").Queries("number", "{number:[0-9]+}", "target", "{target:[^&]+}", "message", "{message:[^&]+}").HandlerFunc(apihandler)
func apihandler(rw http.ResponseWriter, q *http.Request) {
vars := mux.Vars(q)
log.Println(vars["version"])
log.Println(vars("number"))
log.Println(vars("target"))
log.Println(vars("message"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论