Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang HTTP Request returning 200 response but empty body

Tags:

http

go

api

I'm doing a post request and I get a 200 OK response. I also receive the headers. However, the body keeps coming back empty. There should be a body, when I run it in postman the body shows up. What am I missing here?

func AddHealthCheck(baseURL string, payload HealthCheck, platform string, hostname string) (string, error) {
    url := fmt.Sprintf(baseURL+"add-healthcheck/%s/%s", platform, hostname)

    //convert go struct to json
    jsonPayload, err := json.Marshal(payload)
    if err != nil {
        log.Error("[ADD HEALTH CHECK] Could not convert go struct to json : ", err)
        return "", err
    }

    // Create client & set timeout
    client := &http.Client{}
    client.Timeout = time.Second * 15

    // Create request
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload))
    if err != nil {
        log.Error("[ADD HEALTH CHECK] Could not create request : ", err)
        return "", err
    }
    req.Header.Set("Content-Type", "application/json")

    // Fetch Request
    resp, err := client.Do(req)
    if err != nil {
        log.Error("[ADD HEALTH CHECK] Could not fetch request : ", err)
        return "", err
    }
    defer resp.Body.Close()

    // Read Response Body
    respBody, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        log.Error("[HEALTH CHECK] Could not read response body : ", err)
        return "", err
    }

    fmt.Println("response Status : ", resp.Status)
    fmt.Println("response Headers : ", resp.Header)
    fmt.Println("response Body : ", string(respBody))

    return string(respBody), nil
}
like image 273
Lin0523 Avatar asked Oct 12 '18 07:10

Lin0523


People also ask

Can HTTP response have empty body?

All responses to the HEAD request method MUST NOT include a message-body, even though the presence of entity- header fields might lead one to believe they do. All 1xx (informational), 204 (no content), and 304 (not modified) responses MUST NOT include a message-body.

How do I send HTTP POST request in Golang?

Using the "net/http" package, we can make a HTTP POST request. During this post request, we can send JSON data in binary format using the "json" package. The following code shows how we can make the create user request on server "reqres.in", by sending the USER JSON object.


1 Answers

I have confirmed locally that your code, as shown, should work.

Here is the code I used:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "time"
)

func main() {
    http.HandleFunc("/", handler)
    go func(){
        http.ListenAndServe(":8080", nil)
    }()

    AddHealthCheck()
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there")
}

func panicError(err error) {
    if err != nil {
        panic(err)
    }
}

func AddHealthCheck() (string, error) {

    //convert go struct to json
    payload := "bob"
    jsonPayload, err := json.Marshal(payload)
    panicError(err)

    // Create client & set timeout
    client := &http.Client{}
    client.Timeout = time.Second * 15

    // Create request
    req, err := http.NewRequest("POST", "http://localhost:8080", bytes.NewBuffer(jsonPayload))
    panicError(err)
    req.Header.Set("Content-Type", "application/json")

    // Fetch Request
    resp, err := client.Do(req)
    panicError(err)
    defer resp.Body.Close()

    // Read Response Body
    respBody, err := ioutil.ReadAll(resp.Body)
    panicError(err)

    fmt.Println("response Status : ", resp.Status)
    fmt.Println("response Headers : ", resp.Header)
    fmt.Println("response Body : ", string(respBody))

    return string(respBody), nil
}

The code above is just a slightly stripped down version of your code, and it outputs the body of the response. (Note that I provide a server here to receive the post request and return a response)

The server is simply not sending you a body. You can confirm this with something like wireshark.

If you are getting a body back using postman, you must be sending a different request in postman than in go. It can sometimes be tough to see what is the difference, as both go and postman can sometimes add headers behind the scenes that you don't see. Again, something like wireshark can help here.

Or if you have access to the server, you can add logs there.

like image 57
ouidevelop Avatar answered Nov 15 '22 04:11

ouidevelop