亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

是否有將整個 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 關注
  • 242 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號