SQDK
SQDK

Reputation: 4247

Posting json data to remote server with http.Post

I am stumped on what seems like a very simple problem.

I am receiving a json object from a client. It looks like this:

{
    "user": "[email protected]"
}

I need to simply pass this on to another part of the api as a POST request. This is what i've got until now:

//Decode incomming json
decoder := json.NewDecoder(r.Body)
var user UserInformation
err := decoder.Decode(&user)

if err != nil {
    log.Println(err)
}

jsonUser, _ := json.Marshal(user)

log.Println(string(jsonUser[:])) //Correct output
buffer := bytes.NewBuffer(jsonUser)
log.Println(string(buffer.Bytes()[:])) //Also correct


resp, err := http.Post("http://example.com/api/has_publisher", "application/json", buffer)
if err != nil {
    log.Println(err)
}

As I cannot test this program on a live system, I verified the resulting post request with wireshark only to find that the content is missing along with Content-Length being 0. For some reason, http.Post doesn't read from the buffer.

Am i missing something here? I would greatly appreciate if someone could point me in the right direction.

Thanks!

Upvotes: 1

Views: 608

Answers (1)

Sebastian
Sebastian

Reputation: 17453

Shouldn`t be the root cause but replace

buffer := bytes.NewBuffer(jsonUser)

with

buffer := bytes.NewReader(jsonUser)

It is more likely that your test setup is the root cause. I assume you are pointing to a non-existing endpoint. This would result in a failure (TCP SYN fails) before the actual HTTP POST is send.

Check if you can use mockable.io as an alternative to mock your backend.

Upvotes: 2

Related Questions