Reputation: 1201
I have a struct which I have to send to an api and it's a post request. But the input are form field. And the fields contains strings, integer, float and image. I tried to use WriteField function but since this function only takes strings as parameters, I can't process integer and float. How do I do that. Here is my struct and the code snippet.
c := finalObject{
name: Name,
ProfilePic:"/img/unknown.jpg",
owner:"Mr Hall",
latitude:26.5473828,
longitude:88.4249179,
opendays:"Monday-Friday",
openhours:"10am to 5pm",
catId:82,
address:address,
phone_number:2312312,
mobile_number:312312,
email:"[email protected]",
}
url := "https://abcd.com/a"
fmt.Println("URL:>", url)
b, err := json.Marshal(c)
if err != nil {
fmt.Println("error:", err)
}
os.Stdout.Write(b)
var jsonStr = []byte(b)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Authorization", "AUTH_TOKEN")
req.Header.Set("enctype", "multipart/form-data")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
fmt.Printf("%#v", c);
}
Upvotes: 3
Views: 3501
Reputation: 11
The Form values in HTTP form are sent as string values only.
If you have the liberty of deciding the form keys as well then you can add the whole structure as a json-encoded string against a generic "data" field and send the request. Else, you'd have to convert the structure values to string representation to send them in request.
Upvotes: 1