0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

分析屋が異世界転生してエンジニアになったAdvent Calendar 2022

Day 22

Go(gin)のテストで配列をFormDataとしてPostしたい

Last updated at Posted at 2022-12-21

はじめに

タイトルの件で調べても解決に時間がかかってしまったので簡単にまとめてみます

解決方法

  • url.Valuesに"配列をpostする際は{"1", "2"}と書く
  • 構造体のタグにformを指定する
  • Bindする
hoge_controller_test.go
	t.Run("hogeが作成されること", func(t *testing.T) {
		r := controllers.StartMainServer()
		formData := url.Values{
			"form1": {"1", "2"},
	}
		
		req, _ := http.NewRequest("POST", "/hoge_new", strings.NewReader(formData.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		test := httptest.NewRecorder()
		r.ServeHTTP(test, req)
		assert.Equal(t, 200, test.Code)
	})

hoge_controller.go
type Form struct {
	Form1 []string  `form:"form1"`
}

func hoge_new (c *gin.Context) {
	var f Form
	c.Bind(&f)

	fmt.Println(f.Form1)

	c.JSON(200, "OK")
}

以下のように配列で受け取ることが確認できました

image.png

おわりに

url.Valuesに配列を指定する書き方が分からずに詰まってしまいました

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?