首頁  >  文章  >  後端開發  >  如何在 Golang 中將基本 JSON 作為 multipart/form-data 發布

如何在 Golang 中將基本 JSON 作為 multipart/form-data 發布

WBOY
WBOY轉載
2024-02-08 21:03:131084瀏覽

如何在 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 發布的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除