Gorilla Mux用于处理curl请求。

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

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的表单值,而无法获取到targetmessage的值。

使用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"))
}

huangapple
  • 本文由 发表于 2015年2月8日 03:28:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/28386387.html
匿名

发表评论

匿名网友

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

确定