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

7

我正在进行一次POST请求,收到200 OK的响应,同时也收到了相应的头信息。然而,请求体始终为空。

在Postman中运行时,应该会有请求体返回。我错过了什么呢?

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
}

我不确定,但这可能是问题所在。NewRequest函数需要Reader,而你正在传递一个Buffer - Dhirendra
1
@Dhirendra Buffer 实现了 Reader。 - Adrian
1个回答

5

我已经在本地确认,您提供的代码应该可以正常工作。

这是我使用的代码:

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
}

上面的代码只是您的代码稍微简化了一下,它输出响应的主体。(请注意,我在这里提供了一个服务器来接收post请求并返回响应)
服务器只是没有向您发送主体。您可以通过使用wireshark之类的工具来确认此信息。
如果您在postman中返回主体,则必须在postman中发送与go不同的请求。有时很难看出差异,因为go和postman有时会在幕后添加您看不到的标头。再次,使用wireshark之类的工具可以帮助解决问题。
或者,如果您可以访问服务器,则可以在那里添加日志记录。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接