Home > Backend Development > Golang > How to publish basic JSON as multipart/form-data in Golang

How to publish basic JSON as multipart/form-data in Golang

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2024-02-08 21:03:13
forward
1176 people have browsed it

如何在 Golang 中将基本 JSON 作为 multipart/form-data 发布

Question content

I'm dealing with a very frustrating endpoint that requires me to use multipart/form-data as content type for post, even though the endpoint really only requires the basic key:value text for any part of the form. I want to use the basic golang http library.

Unfortunately, any examples I've seen are for more complex types - files, images, videos, etc. What I ended up putting into the body was a simple map[string] interface{}, where interface{} is a simple go type - string, bool, int, float64, etc. . How do I convert this interface into something that the newrequest function will take? Thanks!

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

Copy after login


Correct answer


Based on this answerfor different questions, I was able to figure out what I needed. I had to use the multipart library and set the borders correctly on the header.

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()}
Copy after login

The above is the detailed content of How to publish basic JSON as multipart/form-data in Golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template