最佳实践:r.PostFormValue(“key”) VS r.PostForm.Get(“key”)

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

Best Practice: r.PostFormValue("key") VS r.PostForm.Get("key")

问题

当我查看如何读取表单数据的示例时,我发现有两种读取POST表单值的方法:

使用r.PostFormValue()

username := r.PostFormValue("username")
password := r.PostFormValue("password")

使用r.PostForm.Get()

username := r.PostForm.Get("username")
password := r.PostForm.Get("password")

为什么要选择其中一种而不是另一种呢?

英文:

When I looked at examples how to read form data, I came across two ways to read a post forms value:

Using r.PostFormValue()

username := r.PostFormValue("username")
password := r.PostFormValue("password")

Using r.PostForm.Get()

username := r.PostForm.Get("username")
password := r.PostForm.Get("password")

Why use one over the other?

答案1

得分: 3

Request.PostFormValue()Request.PostForm.Get()都返回相同的值,主要区别在于Request.PostForm不会自动填充。

Request.PostForm是一个表单数据的映射,通过调用Request.ParseMultipartForm()Request.ParseForm()来填充。这不会自动发生,因为这需要读取和解析请求体,而且在所有情况下都可能不需要。

Request.PostFormValue()会在必要时(如果之前没有调用过)调用ParseMultipartForm()ParseForm()来确保Request.PostForm被填充。Request.PostForm是一个选择器,表示RequestPostForm字段,因此它不涉及调用ParseForm()。它假设你已经这样做了。如果你没有这样做,任何PostForm.Get()调用将“静默”返回一个空字符串。

因此,只有在已经解析了表单数据的情况下(例如通过显式调用Request.ParseForm()或间接通过之前的Request.PostFormValue()调用),才应该使用Request.PostForm.Get()

英文:

Both Request.PostFormValue() and Request.PostForm.Get() return the same value, the main difference is that Request.PostForm is not populated automatically.

Request.PostForm is a map of form data, which is populated by calling Request.ParseMultipartForm() or Request.ParseForm(). This doesn't happen automatically, because this requires reading and parsing the request body, and this may not be wanted in all cases.

Request.PostFormValue() calls ParseMultipartForm() and ParseForm() if necessary (if it hasn't been called prior) to ensure Request.PostForm is populated. Request.PostForm is a selector denoting the Request's PostForm field, and as such, it does not involve calling ParseForm(). It assumes you've already done that. If you haven't, any PostForm.Get() calls will "silently" return an empty string.

So you should only use Request.PostForm.Get() if you've already parsed the form data (e.g. by explicitly calling Request.ParseForm() or indirectly via a prior Request.PostFormValue() call).

huangapple
  • 本文由 发表于 2021年12月29日 06:16:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/70513115.html
匿名

发表评论

匿名网友

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

确定