登录
首页 >  Golang >  Go问答

使用Golang将基本JSON作为multipart/form-data发布的方法

来源:stackoverflow

时间:2024-02-11 14:33:17 199浏览 收藏

小伙伴们对Golang编程感兴趣吗?是否正在学习相关知识点?如果是,那么本文《使用Golang将基本JSON作为multipart/form-data发布的方法》,就很适合你,本篇文章讲解的知识点主要包括。在之后的文章中也会多多分享相关知识点,希望对大家的知识积累有所帮助!

问题内容

我正在处理一个非常令人沮丧的端点,它要求我使用 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()}

终于介绍完啦!小伙伴们,这篇关于《使用Golang将基本JSON作为multipart/form-data发布的方法》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>