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

huangapple go评论84阅读模式
英文:

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

问题

我正在处理一个非常令人沮丧的端点,它要求我使用multipart/form-data作为Content-Type进行POST请求,尽管实际上该端点只需要表单中任何部分的基本键值文本。我想使用基本的Golang http库。

不幸的是,我看到的任何示例都是针对更复杂的类型 - 文件、图像、视频等。我要放入请求体中的内容是一个简单的map[string]interface{},其中interface{}是简单的go类型 - string、bool、int、float64等。我该如何将这个接口转换为NewRequest函数可以接受的内容?谢谢!


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 {
          // 处理错误
}

req.Header.Set("Content-Type", "multipart/form-data")
    
client := http.Client{}
rsp, err := client.Do(req)
// 处理剩下的部分

英文:

I'm dealing with a very frustrating endpoint that requires me to use multipart/form-data as the Content-Type to POST, even though the endpoint just realistically wants basic key:value text for any parts of the form. I'd like to use the basic Golang http library.

Unfortunately, any example I've otherwise seen is for more complicated types - files, images, videos, etc. What I have on my end to put into the body is a simple map[string]interface{} where the interface{} is simple go types - string, bool, int, float64, etc. How do I convert this interface into something that the NewRequest func 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

答案1

得分: 0

根据这个答案中的内容,我能够找到我所需要的解决方法。我需要使用multipart库,并在头部正确设置一个边界。


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 {
// 处理错误
}

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

Based on this answer for a different question, I was able to figure out what I needed. I had to use the multipart library and also properly set a boundary 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()}

huangapple
  • 本文由 发表于 2023年3月8日 09:38:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75668718.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定