为了账号安全,请及时绑定邮箱和手机立即绑定

如何通过 Postman 在 go lang 中处理 GET 操作(CRUD)?

如何通过 Postman 在 go lang 中处理 GET 操作(CRUD)?

Go
人到中年有点甜 2021-11-15 20:41:30
我想执行一个获取操作。我将名称作为资源传递给 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)提前致谢。
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

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


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


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


标准库:


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>以这种方式实现更复杂的路径(例如)会很乏味。


另一种方法是使用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.


查看完整回答
反对 回复 2021-11-15
  • 1 回答
  • 0 关注
  • 240 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信