-1

I have an POST API that accepts a json file and a string value as multipart/form-data content-type body.

How do I convert a struct in Golang as json file to send as POST http request?

Example of the struct:

data := map[string]interface{}{
    "type": "doc",
    "name": "test_doc",
    "ids": []string{
      "user1",
      "user2",
    },
    "isFlagged": true,
}

I would need this to be json file as part of the request body for form-data content-type without actually storing the file locally.

Clueless_Coder
  • 515
  • 2
  • 7
  • 16
  • Use `json.Marshall` as this. `b, err := json.Marshal(data)` – N.F. Aug 22 '23 at 06:09
  • This could be helpful: https://stackoverflow.com/questions/50774176/sending-file-and-json-in-post-multipart-form-data-request-with-axios – xerocool Aug 22 '23 at 07:05

1 Answers1

-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
}
M Geppert
  • 9
  • 1