在 Content-Type multipart/form-data Golang 中从结构和 POST 创建 json 文件

问题描述 投票:0回答:1

我有一个 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 文件作为表单数据内容类型的请求正文的一部分,而不实际在本地存储该文件。

json go multipartform-data
1个回答
-1
投票
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
}
© www.soinside.com 2019 - 2024. All rights reserved.