programming

05 How to Used Request Form Post in Golang

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.

func FormPostHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		panic(err)
	}

	firstName := r.PostForm.Get("first_name")
	lastName := r.PostForm.Get("last_name")
	fmt.Fprintf(w, "%s %s", firstName, lastName)
}

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.

func TestFormPostHandler(t *testing.T) {
	type args struct {
		firstName string
		lastName  string
	}
	tests := []struct {
		name string
		args args
		want string
	}{
		{
			name: "set form post param",
			args: args{
				firstName: "ihsan",
				lastName:  "arif",
			},
			want: "ihsan arif",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			requestBody := strings.NewReader(fmt.Sprintf("first_name=%s&last_name=%s", tt.args.firstName, tt.args.lastName))
			request := httptest.NewRequest(http.MethodPost, "http://localhost/say", requestBody)
			request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
			recorder := httptest.NewRecorder()
			FormPostHandler(recorder, request)

			response := recorder.Result()
			body, _ := io.ReadAll(response.Body)
			bodyString := string(body)

			if !reflect.DeepEqual(bodyString, tt.want) {
				t.Errorf("bodyString = %v, want %v", bodyString, tt.want)
			}
		})
	}
}
comments powered by Disqus