0

I'm trying to make unit testing for my Go application that handles form data in multipart/form-data content type using gin (PostForm and PostFormArray) like

x, y := c.PostForm("x"), c.PostFormArray("y")

I have no problem on making a form field which have non-array value (PostForm) with mime/multipart library which Go provides like this

buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)

x, _ := w.CreateFormField("x")
x.Write([]byte("This is x value"))

w.Close()

which PostForm handles perfectly, now I'm wondering if there is any way to send a multipart/form-data field with an array as its value like []string{"this is y 1", "this is y 2"} for it to work with gin's PostFormArray. Is it possible and how do I do it? Any help would be greatly appreciated. Thanks in advance!

4
  • 1
    "send a multipart/form-data field with an array as its value" this is not how multipart works. multipart has no notion of "array". What exactly do you want to send? Commented Aug 11, 2020 at 12:32
  • 2
    Have you tried y1, _ := w.CreateFormField("y") then y1.Write([]byte("this is y 1")), and y2, _ := w.CreateFormField("y") then y2.Write([]byte("this is y 2"))? Commented Aug 11, 2020 at 12:38
  • @Volker I want to send a form field which can work with gin's PostFormArray, which basically means a key with multiple values I guess Commented Aug 12, 2020 at 3:20
  • @mkopriva Thanks, that does the trick! Can't believe I missed this hahahaha, if you want you can post your answer and I'll accept your answer Commented Aug 12, 2020 at 3:21

1 Answer 1

3

You can create multiple fields with the same name, e.g.

buf := new(bytes.Buffer)
w := multipart.NewWriter(buf)

x, _ := w.CreateFormField("x")
x.Write([]byte("This is x value"))

y1, _ := w.CreateFormField("y")
y1.Write([]byte("this is y 1"))

y2, _ := w.CreateFormField("y")
y2.Write([]byte("this is y 2"))

w.Close()
Sign up to request clarification or add additional context in comments.

1 Comment

The simplest and to the point solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.