3

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);
  }
2
  • Turning ints and floats into strings is as simple as fmt.Sprintf("%d", i) and fmt.Sprintf("%f", f) so this cannot be the problem, or? Commented Sep 19, 2017 at 6:35
  • server expect multipart/form-data @CeriseLimón Commented Sep 19, 2017 at 6:41

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

But how do I convert a struct into String
b, err := json.Marshal(c) b which is a byte array can be typecast in a string variable and then again typecast and unmarshalled at server end

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.