为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 Golang 中的 http 响应中读取压缩数据

如何从 Golang 中的 http 响应中读取压缩数据

Go
LEATH 2023-04-24 15:35:50
我有一个 gzip 压缩的 http 响应。resp, err := client.Do(req)    if err != nil {        return "", err    }    defer resp.Body.Close()    if resp.StatusCode == http.StatusOK {        var buf bytes.Buffer    }我如何解压缩它并将其解析到我的结构中?我看到了这样一个问题: Reading gzipped HTTP response in Go但它将响应输出到标准输出中。这个例子也遇到了错误,reader, err = gzip.NewReader(response.Body)将错误返回为“EOF”。我该如何调试呢?
查看完整描述

1 回答

?
POPMUISE

TA贡献1765条经验 获得超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 之类的工具来确认这一点。


如果您使用邮递员取回身体,则必须在邮递员中发送与在 go 中不同的请求。有时很难看出有什么区别,因为 go 和 postman 有时会在幕后添加您看不到的标题。同样,wireshark 之类的工具在这里可以提供帮助。


或者,如果您有权访问服务器,则可以在其中添加日志。


查看完整回答
反对 回复 2023-04-24
  • 1 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信