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

我想执行一个获取操作。我将名称作为资源传递给 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)

提前致谢。


人到中年有点甜
浏览 241回答 1
1回答

阿波罗的战车

您正在做的是绑定要处理的完整路径。/location/{titan rolex}GetUser您真正想要的是绑定/location/<every possible string>以由一个处理程序处理(例如LocationHandler)。您可以使用标准库或其他路由器来做到这一点。我将介绍两种方式:标准库:import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "log")func locationHandler(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; name := r.URL.Path[len("/location/"):]&nbsp; &nbsp; fmt.Fprintf(w, "Location: %s\n", name)}func main() {&nbsp; &nbsp; http.HandleFunc("/location/", locationHandler)&nbsp; &nbsp; log.Fatal(http.ListenAndServe(":8080", nil))}但是请注意,/location/<every possible string>/<some int>/<another string>以这种方式实现更复杂的路径(例如)会很乏味。另一种方法是使用github.com/julienschmidt/httprouter,特别是如果您更频繁地遇到这些情况(并且路径更复杂)。以下是您的用例的示例:import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "github.com/julienschmidt/httprouter"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "log")func LocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {&nbsp; &nbsp; fmt.Fprintf(w, "Location: %s\n", ps.ByName("loc"))}func main() {&nbsp; &nbsp; router := httprouter.New()&nbsp; &nbsp; router.GET("/location/:loc", LocationHandler)&nbsp; &nbsp; log.Fatal(http.ListenAndServe(":8080", router))}请注意,httprouter对处理程序使用稍微不同的签名。这是因为,如您所见,它还将这些参数传递给函数。哦,还有一个注意事项,你可以直接http://localhost:8080/location/titan rolex用你的浏览器(或其他东西)点击 - 如果其他东西足够好,它会将 URLEncode 编码为http://localhost:8080/location/titan%20rolex.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go