英文:
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
是一个选择器,表示Request
的PostForm
字段,因此它不涉及调用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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论