Go Gorilla mux 处理 API 个请求
Go Gorilla mux to handles API requests
我想从以下 Gorilla Mux 路由器获取地图结构 input.package main
例如,
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"
你要我做吗?
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"))
}
您可以在路由器上使用查询方法
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)
}
我想从以下 Gorilla Mux 路由器获取地图结构 input.package main
例如,
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"
你要我做吗?
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"))
}
您可以在路由器上使用查询方法
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)
}