Notes on Form Types in Go Web

2022年5月29日 3595点热度 1人点赞 1条评论
内容目录

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

file

ParseForm()

Now let's test r.ParseForm().

Test code:

	r.ParseForm()
	fmt.Println(r.Form)
	fmt.Println(r.PostForm)
	fmt.Println(r.MultipartForm)

file

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)

file

As seen, all forms are normal.

x-www-form-urlencoded

file

ParseForm()

Now let's test r.ParseForm().

Test code:

	r.ParseForm()
	fmt.Println(r.Form)
	fmt.Println(r.PostForm)
	fmt.Println(r.MultipartForm)

file

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)

file

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)

痴者工良

高级程序员劝退师

文章评论