Post request not with json data

I’m trying to write a function that will make a (curl) POST request to a remote service. the data is sent NOT as a json string but rather as a string url params:


in PHP I do it like this:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiUrl);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($dataArray));
$result = curl_exec($ch);

in GO I tried copying examples from the internet, non of them work… looks like the params i’m sending aren’t really sent, or something gets lost because the service returns error that mandatory params are missing…

here’s my attempt:

    url := ""
    postData := strings.NewReader(

    req, err := http.NewRequest("POST", url, postData)
    if err != nil {

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
    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))

this version seems to work, even though i have other issues somewhere and the response claims 1 of my params is wrong… however in postman i put the same params and it works…

 apiUrl  := ""
    resource := "/Api/"
	data := url.Values{}
	data.Set("param1", "1")
        data.Add("param2", "2")

 	u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := fmt.Sprintf("%v", u) 

    client := &http.Client{}
    r, _ := http.NewRequest("POST", urlStr, bytes.NewBufferString(data.Encode())) 
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))

Please check every single error value. We cannot help you til this is done.

1 Like

Once you’ve done that, please update your question to include these two sections.

  1. What did you expect to see when you ran your code?
  2. What did you see instead?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.