Basics
There are three types of forms in Go Web:
r.Form
r.PostForm
r.MultipartForm
PostForm
supports form-data
and x-www-form-urlencoded
request bodies, but does not support file uploads.
MultipartForm
only supports form-data
request bodies, but supports file uploads.
Form
contains a collection of both URL Query and PostForm
.
There are two parsing methods:
r.ParseForm()
r.ParseMultipartForm(1 << 20) // The value of 1<<20 should be set accordingly
When executing ParseForm()
, it will also parse PostForm
.
ParseForm
->Form
->PostForm
When executing ParseMultipartForm()
, it will also execute ParseForm
.
ParseMultipartForm
->MultipartForm
->Form
->PostForm
form-data
ParseForm()
Now let's test r.ParseForm()
.
Test code:
r.ParseForm()
fmt.Println(r.Form)
fmt.Println(r.PostForm)
fmt.Println(r.MultipartForm)
In addition to being able to receive URL Query, both PostForm
and MultipartForm
have no data.
ParseMultipartForm()
Now let's test r.ParseMultipartForm()
.
r.ParseMultipartForm(1 << 20)
fmt.Println(r.Form)
fmt.Println(r.PostForm)
fmt.Println(r.MultipartForm)
As seen, all forms are normal.
x-www-form-urlencoded
ParseForm()
Now let's test r.ParseForm()
.
Test code:
r.ParseForm()
fmt.Println(r.Form)
fmt.Println(r.PostForm)
fmt.Println(r.MultipartForm)
We can see that both Form
and PostForm
are normal, while MultipartForm
has no data.
ParseMultipartForm()
Now let's test r.ParseMultipartForm()
.
r.ParseMultipartForm(1 << 20)
fmt.Println(r.Form)
fmt.Println(r.PostForm)
fmt.Println(r.MultipartForm)
We can see that both Form
and PostForm
are normal, while MultipartForm
has no data.
How to Use
Since x-www-form-urlencoded
performs better than form-data
, if file uploads are not needed, use the following combination:
content-type: x-www-form-urlencoded
r.ParseForm()
fmt.Println(r.PostForm)
If file uploads are needed, use this combination:
content-type: form-data
r.ParseMultipartForm(1 << 20)
fmt.Println(r.MultipartForm)
文章评论