Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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?

like image 933
Alex Avatar asked Feb 09 '23 02:02

Alex


1 Answers

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.

like image 196
Sudhir Jonathan Avatar answered Feb 11 '23 23:02

Sudhir Jonathan