【问题标题】:Go Gorilla mux to handles API requestsGo Gorilla mux 处理 API 请求
【发布时间】:2015-04-02 05:21:23
【问题描述】:

我想从下面的 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"

【问题讨论】:

    标签: web-applications go router mux gorilla


    【解决方案1】:

    你要我做吗?

    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】:

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

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

      Documentation

      【讨论】:

        猜你喜欢
        • 2015-04-07
        • 2014-11-28
        • 2015-05-03
        • 2014-12-22
        • 2017-06-14
        • 2014-12-21
        • 1970-01-01
        • 1970-01-01
        • 2015-04-18
        相关资源
        最近更新 更多