Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Created October 4, 2018 14:52
Show Gist options
  • Save jooyunghan/e9966856572cdff1493146a79b1bfcaf to your computer and use it in GitHub Desktop.
Save jooyunghan/e9966856572cdff1493146a79b1bfcaf to your computer and use it in GitHub Desktop.
multipart writer example with json
package main
import (
"bytes"
"encoding/json"
"fmt"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/http"
"net/textproto"
"strings"
)
var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
func escapeQuotes(s string) string {
return quoteEscaper.Replace(s)
}
func writeJSON(w *multipart.Writer, name string, v interface{}) error {
header := textproto.MIMEHeader{}
header.Add("Content-Disposition", fmt.Sprintf("form-data; name=\"%s\"", escapeQuotes(name)))
header.Add("Content-Type", mime.FormatMediaType("application/json", map[string]string{"charset": "UTF-8"}))
header.Add("Content-Transfer-Encoding", "quoted-printable")
pw, err := w.CreatePart(header)
if err != nil {
return err
}
qpw := quotedprintable.NewWriter(pw)
encoder := json.NewEncoder(qpw)
return encoder.Encode(v)
}
func main() {
b := &bytes.Buffer{}
writer := multipart.NewWriter(b)
writeJSON(writer, "xx", map[string]string{
"한글키": "값",
})
ww, _ := writer.CreateFormFile("yy", "a.jpg")
ww.Write([]byte{1, 2, 3})
writer.Close()
fmt.Println(string(b.Bytes()))
req, _ := http.NewRequest("GET", "localhost", b)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.ParseMultipartForm(1 << 10)
f := req.MultipartForm.File["yy"]
fmt.Println(f)
fmt.Println(req.PostFormValue("xx"))
// r := multipart.NewReader(b, writer.Boundary())
// p, _ := r.NextPart()
// fmt.Println(p.FormName())
// decoder := json.NewDecoder(p)
// var body interface{}
// decoder.Decode(&body)
// fmt.Println(body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment