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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With