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?
CodePudding user response:
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).