3
1

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 5 years have passed since last update.

Golang での multipart な RequestBody のつくりかた

Last updated at Posted at 2018-05-17

multipart/related を POST したくて調べたときのメモ。

mime/multipart を使って NewWriter して (CreatePart して)+ Close すればOK🙆

package main

import (
	"bytes"
	"fmt"
	"mime/multipart"
	"net/textproto"
)

func main() {
	body := new(bytes.Buffer)

	mpWriter := multipart.NewWriter(body)

	boundary := "END_OF_PART"
	if err := mpWriter.SetBoundary(boundary); err != nil {
		panic(err)
	}

	{
		part := make(textproto.MIMEHeader)
		part.Set("Content-Type", "text/plain")

		writer, err := mpWriter.CreatePart(part)
		if err != nil {
			panic(err)
		}

		writer.Write([]byte("hello"))
	}
	
	{
		part := make(textproto.MIMEHeader)
		part.Set("Content-Type", "text/plain")

		writer, err := mpWriter.CreatePart(part)
		if err != nil {
			panic(err)
		}

		writer.Write([]byte("hello2"))
	}

	mpWriter.Close()

	fmt.Println(body)
}

OUTPUT

--END_OF_PART
Content-Type: text/plain

hello
--END_OF_PART
Content-Type: text/plain

hello2
--END_OF_PART--
  • 複数の Part を書き込むには、CreatePart を何度も呼び出せばよい
  • Part の中身は、CreatePart から返ってくる io.Writer で書き込める
  • Boundary は指定しなければ生成してくれるみたい
  • Close しないと最後の区切り --<Boundary>-- が書き込まれないので注意🚨

Playground

References

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?