英文:
Go Gorilla mux to handles API requests
问题
我想从以下 Gorilla Mux 路由器输入中获取地图结构。
例如,
router.Methods("GET").Path("/api/{action}").HandlerFunc(httpLog(myHandler))
func myHandler(rw http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println(vars["action"])
}
服务于 0.0.0.0:3000/api/input
,并打印出字符串 input
。
如果我想能够接收如下请求:
0.0.0.0:3000/api/v3?id=hello&password=great&product=ipad&confirm=true
并且从这个请求中,我想得到一个地图:
map["id"] = "hello"
map["password"] = "great"
map["product"] = "ipad"
map["confirm"] = "true"
英文:
I want to get the map structure from the following Gorilla Mux router input.package main
For example,
router.Methods("GET").Path("/api/{action}").HandlerFunc(httpLog(myHandler))
func myHandler(rw http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println(vars["action"])
}
Serves 0.0.0.0:3000/api/input
and this prints out the string input
What if I want to be able to receive requests like:
0.0.0.0:3000/api/v3?id=hello&password=great&product=ipad&confirm=true
And from this requests, I want to get a map of:
map["id"] = "hello"
map["password"] = "great"
map["product"] = "ipad"
map["confirm"] = "true"
答案1
得分: 0
你想让我做什么?
func myHandler(r http.ResponseWriter, q *http.Request) {
vars := mux.Vars(q)
fmt.Println(vars["action"])
fmt.Println(q.FormValue("id"))
fmt.Println(q.FormValue("password"))
fmt.Println(q.FormValue("product"))
fmt.Println(q.FormValue("confirm"))
}
请注意,这是一个Go语言的代码片段,它接收一个HTTP请求并打印出一些参数的值。
英文:
Will you want me to do?
func myHandler(r http.ResponseWriter, q *http.Request) {
vars := mux.Vars(q)
fmt.Println(vars["action"])
fmt.Println(q.FormValue("id"))
fmt.Println(q.FormValue("password"))
fmt.Println(q.FormValue("product"))
fmt.Println(q.FormValue("confirm"))
}
答案2
得分: 0
你可以在你的路由器上使用Queries方法。
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter().Queries("id", "{id:[a-z]+}", "password", "{password:[a-z]+}", "product", "{product:[a-z]+}", "confirm", "{confirm:true|false}")
request, _ := http.NewRequest("GET", "http://example.com?id=hello&password=great&product=ipad&confirm=true", nil)
var match mux.RouteMatch
router.Match(request, &match)
fmt.Println(match.Vars)
}
英文:
You can use Queries method on you router
package main
import (
"fmt"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter().Queries("id", "{id:[a-z]+}", "password", "{password:[a-z]+}", "product", "{product:[a-z]+}", "confirm", "{confirm:true|false}")
request, _ := http.NewRequest("GET", "http://example.com?id=hello&password=great&product=ipad&confirm=true", nil)
var match mux.RouteMatch
router.Match(request, &match)
fmt.Println(match.Vars)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论