Golang获取mux值

huangapple go评论71阅读模式
英文:

Golang get mux value

问题

我是你的中文翻译助手,以下是翻译好的内容:

我是Go语言的新手。我正在使用mux并尝试解析URL参数。我有以下代码,其中r是一个*http.Request

vars := mux.Vars(r)
user := vars["user"]
fmt.Print(user)

mux获取整个URL参数字符串,如下所示的打印输出:

"user=username"

我想知道是否可以直接获取值(username),还是需要使用正则表达式来获取用户名。

谢谢任何帮助!

英文:

I'm new to go. I'm using mux and trying to parse out a url parameter. I have the following code where r is a *http.Request

vars := mux.Vars(r)
user := vars["user"]
fmt.Print(user)

mux grabs the whole url parameter string like the following print out.

> "user=username"

I'm wondering if it's possible to simply grab the value (username), or if I need to do regex to get the username.

Thanks for any help!!

答案1

得分: 2

Mux的Vars属性更适用于解析路径变量,例如user/{id},并能够提取出该信息。对于实际的URL查询参数,最好使用内置的请求Query()对象。

user := r.URL.Query().Get("user")
英文:

Mux's Vars attribute is more for parsing path variables such as user/{id} and being able to extract out that information. For actual URL query parameters, you're better off using the built-in request Query() object.

user := r.URL.Query().Get("user")

huangapple
  • 本文由 发表于 2022年6月24日 03:01:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/72735344.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定