1

我想从以下 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"
4

2 回答 2

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"))     
}
于 2015-02-03T06:17:00.713 回答
0

您可以在路由器上使用查询方法

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)
}

文档

于 2015-02-03T06:24:55.890 回答