转到:从http.Request获取路径参数 [英] Go: Get path parameters from http.Request

查看:359
本文介绍了转到:从http.Request获取路径参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



I想要这样的东西:

  func main(){
http.HandleFunc(/ provisions /:id,规定)//< - 如何在路径中映射id参数?
http.ListenAndServe(:8080,nil)
}

func规定(w http.ResponseWriter,r * http.Request){
// I想从请求中获取这里的id参数
}

我想用如果可能, http 包而不是web框架。



谢谢。

解决方案

如果您不想使用任何大量可用的路由包,那么您需要自己解析路径:

将/ provisions路径路由到您的处理程序

  http.HandleFunc(/ provisions / ,规定)

然后根据需要在处理程序中分割路径

  id:= strings.TrimPrefix(req.URL.Path,/ provisions /)
//或者使用strings.Split,或者使用regexp等


I'm developing a REST API with Go, but I don't know how can I do the path mappings and retrieve the path parameters from them.

I want something like this:

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
}

I would like to use just http package instead of web frameworks, if it is possible.

Thanks.

解决方案

If you don't want to use any of the multitude of the available routing packages, then you need to parse the path yourself:

Route the /provisions path to your handler

http.HandleFunc("/provisions/", Provisions)

Then split up the path as needed in the handler

id := strings.TrimPrefix(req.URL.Path, "/provisions/")
// or use strings.Split, or use regexp, etc.

这篇关于转到:从http.Request获取路径参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆