Home  >  Article  >  Backend Development  >  How to publish basic JSON as multipart/form-data in Golang

How to publish basic JSON as multipart/form-data in Golang

WBOY
WBOYforward
2024-02-08 21:03:131083browse

如何在 Golang 中将基本 JSON 作为 multipart/form-data 发布

Question content

I'm dealing with a very frustrating endpoint that requires me to use multipart/form-data as content type for post, even though the endpoint really only requires the basic key:value text for any part of the form. I want to use the basic golang http library.

Unfortunately, any examples I've seen are for more complex types - files, images, videos, etc. What I ended up putting into the body was a simple map[string] interface{}, where interface{} is a simple go type - string, bool, int, float64, etc. . How do I convert this interface into something that the newrequest function will take? Thanks!

bodyInput := map[string]interface{}{"client_id":"abc123", "you_ok": false, "jwt_token":"psojioajf.sjfiofijw.asdisaoetcetc"}

req, err := http.NewRequest(http.MethodPost, "https://my-website.com/endpoint/path", ???) // replace ???
if err != nil {
          // handle error 
}

req.Header.Set("Content-Type", "multipart/form-data")
    
client := http.Client{}
rsp, err := client.Do(req)
// deal with the rest


Correct answer


Based on this answerfor different questions, I was able to figure out what I needed. I had to use the multipart library and set the borders correctly on the header.

import (
   "mime/multipart"
)

bodyInput := map[string]interface{}{"client_id":"abc123", "you_ok": false, "jwt_token":"psojioajf.sjfiofijw.asdisaoetcetc"}


reqBody := new(bytes.Buffer)
mp := multipart.NewWriter(reqBody)
for k, v := range bodyInput {
  str, ok := v.(string) 
  if !ok {
    return fmt.Errorf("converting %v to string", v) 
  }
  mp.WriteField(k, str)
}
mp.Close()

req, err := http.NewRequest(http.MethodPost, "https://my-website.com/endpoint/path", reqBody)
if err != nil {
// handle err
}

req.Header["Content-Type"] = []string{mp.FormDataContentType()}

The above is the detailed content of How to publish basic JSON as multipart/form-data in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete