Go:从 http.Request 获取路径参数

我正在使用 Go 开发 REST API,但我不知道如何进行路径映射并从中检索路径参数。


我想要这样的东西:


func main() {

    http.HandleFunc("/provisions/:id", Provisions) //<-- How can I map "id" parameter in the path?

    http.ListenAndServe(":8080", nil)

}


func Provisions(w http.ResponseWriter, r *http.Request) {

    //I want to retrieve here "id" parameter from request

}

http如果可能的话,我只想使用包而不是 Web 框架。


哈士奇WWW
浏览 1759回答 3
3回答

皈依舞

如果您不想使用众多可用的路由包中的任何一个,那么您需要自己解析路径:将 /provisions 路径路由到您的处理程序http.HandleFunc("/provisions/", Provisions)然后在处理程序中根据需要拆分路径id := strings.TrimPrefix(req.URL.Path, "/provisions/")// or use strings.Split, or use regexp, etc.

智慧大石

您可以使用 golang gorilla/mux包的路由器来进行路径映射并从中检索路径参数。import (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "github.com/gorilla/mux"&nbsp; &nbsp; "net/http")func main() {&nbsp; &nbsp; r := mux.NewRouter()&nbsp; &nbsp; r.HandleFunc("/provisions/{id}", Provisions)&nbsp; &nbsp; http.ListenAndServe(":8080", r)}func Provisions(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; vars := mux.Vars(r)&nbsp; &nbsp; id, ok := vars["id"]&nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("id is missing in parameters")&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(`id := `, id)&nbsp; &nbsp; //call http://localhost:8080/provisions/someId in your browser&nbsp; &nbsp; //Output : id := someId}

忽然笑

Golang 从 URL 查询“/template/get/123”中读取值。我使用了标准的 gin 路由和处理来自上下文参数的请求参数。在注册您的端点时使用它:func main() {&nbsp; &nbsp; r := gin.Default()&nbsp; &nbsp; g := r.Group("/api")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; g.GET("/template/get/:Id", templates.TemplateGetIdHandler)&nbsp; &nbsp; }&nbsp; &nbsp; r.Run()}并在处理程序中使用此函数func TemplateGetIdHandler(c *gin.Context) {&nbsp; &nbsp; req := getParam(c, "Id")&nbsp; &nbsp; //your stuff}func getParam(c *gin.Context, paramName string) string {&nbsp; &nbsp; return c.Params.ByName(paramName)}Golang 从 URL 查询“/template/get?id=123”中读取值。在注册您的端点时使用它:func main() {&nbsp; &nbsp; r := gin.Default()&nbsp; &nbsp; g := r.Group("/api")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; g.GET("/template/get", templates.TemplateGetIdHandler)&nbsp; &nbsp; }&nbsp; &nbsp; r.Run()}并在处理程序中使用此函数type TemplateRequest struct {&nbsp; &nbsp; Id string `form:"id"`}func TemplateGetIdHandler(c *gin.Context) {&nbsp; &nbsp; var request TemplateRequest&nbsp; &nbsp; err := c.Bind(&request)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Println(err.Error())&nbsp; &nbsp; &nbsp; &nbsp; c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})&nbsp; &nbsp; }&nbsp; &nbsp; //your stuff}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go