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

是否有将整个 http 响应转换为字节切片的 Go http 方法?

是否有将整个 http 响应转换为字节切片的 Go http 方法?

Go
跃然一笑 2022-07-11 17:26:55
我一直想知道是否已经有一种方法可以将所有的 a 写入http/Responsea []byte?我发现响应指出,body 可以通过 do 轻松转换为 a []byte,ioutil.ReadAll(response.Body)但是是否有一个已经构建的解决方案可以写入所有信息(包括状态代码、标题、预告片等)?我问的原因是因为我希望通过套接字将整个响应传输到客户端,并且库的Write方法net需要一个字节数组。
查看完整描述

1 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

httputil.DumpResponse是您所需要的(也由 Adrian 建议)。以下代码应该会有所帮助:


package main


import (

    "fmt"

    "net/http"

    "net/http/httptest"

    "net/http/httputil"

    "os"

)


func main() {

    // Create a test server

    server := httptest.NewServer(http.HandlerFunc(

        func(w http.ResponseWriter, r *http.Request) {

            // Set Header

            w.Header().Set("HEADER_KEY", "HEADER_VALUE")

            // Set Response Body

            fmt.Fprintln(w, "DUMMY_BODY")

        }))

    defer server.Close()


    // Request to the test server

    resp, err := http.Get(server.URL)

    if err != nil {

        fmt.Fprintln(os.Stderr, err)

        os.Exit(1)

    }

    defer resp.Body.Close()


    // DumpResponse takes two parameters: (resp *http.Response, body bool)

    // where resp is the pointer to the response object. And body is boolean

    // to dump body or not

    dump, err := httputil.DumpResponse(resp, true)

    if err != nil {

        fmt.Fprintln(os.Stderr, err)

        os.Exit(1)

    }

    // Dump the response ([]byte)

    fmt.Printf("%q", dump)

}

输出:


"HTTP/1.1 200 OK\r\nContent-Length: 11\r\nContent-Type: text/plain; charset=utf-8\r\n

Date: Wed, 18 Nov 2020 17:43:40 GMT\r\n

Header_key: HEADER_VALUE\r\n\r\n

DUMMY_BODY\n"


查看完整回答
反对 回复 2022-07-11
  • 1 回答
  • 0 关注
  • 344 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号