dpbv85276 2018-10-12 07:09
浏览 1114
已采纳

Golang HTTP请求返回200响应,但主体为空

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
}
  • 写回答

1条回答 默认 最新

  • doujie7497 2018-10-17 21:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮