Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
28 Aug 2023 · 2 min read ·Article 35 / 119
Go

05 How to Used Request Form Post in Golang

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Introduction to Post Forms

Similar to the previous post, when we use the GET method, the results of all the data in the form will be a param query, whereas if we use POST then all the data in the form is sent via the body of the HTTP Request, only the method is different. All form post data sent from the client will automatically be stored in the Request.PostFrom attribute. However, before we can retrieve the PostForm attribute data, we must first call the Request.ParseForm() method and then this method will be used to parse the body. Parsing this data will produce form data, if it is not there it will cause an error in the parsing.

Implementation

The following is an example of how we implement a Post Form.

go
 1func FormPostHandler(w http.ResponseWriter, r *http.Request) {
 2	err := r.ParseForm()
 3	if err != nil {
 4		panic(err)
 5	}
 6
 7	firstName := r.PostForm.Get("first_name")
 8	lastName := r.PostForm.Get("last_name")
 9	fmt.Fprintf(w, "%s %s", firstName, lastName)
10}

So how do we test whether our handler has been successful or not? As usual, we will test it using the unit tests in Golang. Try right-clicking on the function that we have created then create a unit test and VSCode will automatically create a unit test framework. To understand more, you can see more details below.

go
 1func TestFormPostHandler(t *testing.T) {
 2	type args struct {
 3		firstName string
 4		lastName  string
 5	}
 6	tests := []struct {
 7		name string
 8		args args
 9		want string
10	}{
11		{
12			name: "set form post param",
13			args: args{
14				firstName: "ihsan",
15				lastName:  "arif",
16			},
17			want: "ihsan arif",
18		},
19	}
20	for _, tt := range tests {
21		t.Run(tt.name, func(t *testing.T) {
22			requestBody := strings.NewReader(fmt.Sprintf("first_name=%s&last_name=%s", tt.args.firstName, tt.args.lastName))
23			request := httptest.NewRequest(http.MethodPost, "http://localhost/say", requestBody)
24			request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
25			recorder := httptest.NewRecorder()
26			FormPostHandler(recorder, request)
27
28			response := recorder.Result()
29			body, _ := io.ReadAll(response.Body)
30			bodyString := string(body)
31
32			if !reflect.DeepEqual(bodyString, tt.want) {
33				t.Errorf("bodyString = %v, want %v", bodyString, tt.want)
34			}
35		})
36	}
37}

Related Articles

💬 Comments