我正在处理一个非常令人沮丧的端点,它要求我使用 multipart/form-data
作为 post 的内容类型,即使端点实际上只需要表单的任何部分的基本键:值文本。我想使用基本的 golang http
库。
不幸的是,我见过的任何示例都是针对更复杂的类型 - 文件、图像、视频等。我最终要放入正文中的是一个简单的 map[string] 接口{}
,其中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 {
// handle error
}
req.Header.Set("Content-Type", "multipart/form-data")
client := http.Client{}
rsp, err := client.Do(req)
// deal with the rest
正确答案
根据这个答案针对不同的问题,我能够弄清楚我需要什么。我必须使用 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 {
// handle err
}
req.Header["Content-Type"] = []string{mp.FormDataContentType()}