我有一个 POST API,它接受 json 文件和字符串值作为 multipart/form-data 内容类型主体。
如何将 Golang 中的结构转换为 json 文件以作为 POST http 请求发送?
结构示例:
data := map[string]interface{}{
"type": "doc",
"name": "test_doc",
"ids": []string{
"user1",
"user2",
},
"isFlagged": true,
}
我需要将其作为 json 文件作为表单数据内容类型的请求正文的一部分,而不实际在本地存储该文件。
package main
import (
"encoding/json"
"fmt"
)
type Thing struct {
FileType string `json:"Type"`
Name string `json:"Name"`
Ids []string `json:"IDs"`
IsFlagged bool `json:"Is Flagged"`
}
func main() {
data := Thing{
FileType: "doc",
Name: "test_doc",
Ids: []string{
"user1",
"user2",
},
IsFlagged: true,
}
fmt.Printf("%v\n", data)
b, err := json.Marshal(data)
if err != nil {
fmt.Printf("%v\n", b)
} else {
fmt.Printf("%v\n", b)
}
// then use b to POST http request
}