【问题标题】:How to process GET operation (CRUD) in go lang via Postman?如何通过 Postman 处理 go lang 中的 GET 操作(CRUD)?
【发布时间】:2016-01-20 04:04:29
【问题描述】:

我想执行一个 get 操作。我将名称作为资源传递给 URL。 我在 Postman 中点击的 URL 是:localhost:8080/location/{titan rolex}(我在下拉列表中选择了 GET 方法) 在 Postman 中命中的 URL 上,我正在执行 GetUser func(),正文为:

func GetUser(rw http.ResponseWriter, req *http.Request) {

}

现在我希望在 GetUser 方法中获取资源值,即“titan Rolex”。 如何在 golang 中实现这一点?

在 main() 中,我有这个:

http.HandleFunc("/location/{titan rolex}", GetUser)

提前致谢。

【问题讨论】:

    标签: http go http-get postman


    【解决方案1】:

    您正在做的是绑定 完整 路径 /location/{titan rolex} 以由 GetUser 处理。

    您真正想要的是绑定/location/<every possible string> 以由一个处理程序处理(例如LocationHandler)。

    您可以使用标准库或其他路由器来做到这一点。我将介绍两种方式:

    1. 标准库:

      import (
          "fmt"
          "net/http"
          "log"
      )
      
      func locationHandler(w http.ResponseWriter, r *http.Request) {
          name := r.URL.Path[len("/location/"):]
          fmt.Fprintf(w, "Location: %s\n", name)
      }
      
      func main() {
          http.HandleFunc("/location/", locationHandler)
          log.Fatal(http.ListenAndServe(":8080", nil))
      }
      

      但是请注意,以这种方式实现更复杂的路径(例如 /location/<every possible string>/<some int>/<another string>)会很乏味。

    2. 另一种方法是使用github.com/julienschmidt/httprouter,尤其是当您经常遇到这些情况(并且路径更复杂)时。

      以下是您的用例示例:

      import (
          "fmt"
          "github.com/julienschmidt/httprouter"
          "net/http"
          "log"
      )
      
      func LocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
          fmt.Fprintf(w, "Location: %s\n", ps.ByName("loc"))
      }
      
      func main() {
          router := httprouter.New()
          router.GET("/location/:loc", LocationHandler)
      
          log.Fatal(http.ListenAndServe(":8080", router))
      }
      

      请注意,httprouter 对处理程序使用的签名略有不同。这是因为,如您所见,它还将这些参数传递给函数。

    哦,还有一点,你可以用你的浏览器(或其他东西)点击http://localhost:8080/location/titan rolex - 如果其他东西足够好,它会将URLEncode为http://localhost:8080/location/titan%20rolex

    【讨论】:

    • 非常感谢@mrd0ll4r 的见解。我现在可以获取数据了。所以基本上我认为 r.GET 是比 HnadleFunc 更好的选择。
    • 基本上是一样的——我所做的是在两者之间添加httprouter,谁决定使用什么处理程序。
    • @mrd0ll4r 仅使用 std 库的方法是为 /location/ 注册一个处理程序,该处理程序将匹配 /location/titan rolex 短示例 play.golang.org/p/fyJVDqL2Ox 长示例 golang.org/doc/articles/wiki
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2019-06-27
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多