你应该在什么时候使用ParseForm,以及在什么时候使用FormValue和PostFormValue呢?

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

When should you use ParseForm and when should you use FormValue and PostFormValue?

问题

我只会为你提供翻译服务,以下是你要翻译的内容:

我只是想获取表单数据,但我不太明白应该使用哪种方法。

在这篇文章中:http://astaxie.gitbooks.io/build-web-application-with-golang/content/en/04.1.html

他们使用了r.ParseForm(),并通过r.Form["username"]来获取POST的值。

但是当我在自己的代码中尝试这样做时,它并没有起作用,我得到的是一个字符串切片,所以我不得不使用r.Form["username"][0]来获取字符串值。

为什么这与文章中的方法不同?为什么我得到的是一个字符串切片?

另外还有另一种方法可以这样使用:r.FormValue("username")

还有一个r.PostFormValue("username"),又是另一种方法!

在不同的情况下应该使用哪种方法?

英文:

I am simply trying to get to form data and I don't quite understand which method to use.

In this article: http://astaxie.gitbooks.io/build-web-application-with-golang/content/en/04.1.html

They use r.ParseForm() and get post values by doing r.Form["username"].

But when I tried this in my own code it did not work, I instead got a slice of strings, so I had to do r.Form["username"][0] to get the string value.

Why is that different from the one shown in the article? Why do I get a slice of strings?

Also there is another method which can be used like this r.FormValue("username").

And then there is a r.PostFormValue("username"), another one!

Which one should you use in different situations?

答案1

得分: 8

根据经验,当你知道要读取的键时,只需使用r.PostFormValue("username")。这种方法总是可以正常工作,无需其他准备。只需记住,即使方法是POST,它也不会读取查询参数。

然而,如果你需要检查发送的数据,你需要先使用r.ParseForm()解析数据,然后使用r.Form["username"][0]读取值。对于期望在同一个键上有多个值的情况也是如此。

英文:

As a rule of thumb, just use r.PostFormValue("username") when you know the key you want to read. This method always works without any other preparation. Just remember that this won't read query parameters, though, even if the method was a POST.

If you need to check what data was sent, though, you'll have to first parse the data using r.ParseForm() and then read the values using r.Form["username"][0]. The same goes for cases where you expect multiple values on the same key.

huangapple
  • 本文由 发表于 2015年9月9日 23:46:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/32484028.html
匿名

发表评论

匿名网友

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

确定