Created
          October 4, 2018 14:52 
        
      - 
      
- 
        Save jooyunghan/e9966856572cdff1493146a79b1bfcaf to your computer and use it in GitHub Desktop. 
    multipart writer example with json
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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