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

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

如何使用 RoundTrip 跟蹤請求大小?

為潛在的新手問題道歉,但我正在改編別人的代碼并且不熟悉 Go 語言。在代理 http 請求的代碼中,我有以下部分func handleHTTP(w http.ResponseWriter, req *http.Request) {    resp, err := http.DefaultTransport.RoundTrip(req)..我知道 req 包括一個流式主體,因此沒有立即可用的長度,因為我希望 RoundTrip 讀取這樣的流。我的問題是如何調整這樣的代碼,以便在流完全消耗后獲得請求正文的最終大小......謝謝
查看完整描述

2 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

Request有 aContentLength作為可用屬性,在某些情況下您可能只能使用它。雖然如果請求使用傳輸編碼,我認為這個值設置為 -1(可能為 0)。


否則我認為你可以用你自己的 io.ReadCloser 實現包裝 req.Body 。像這樣:


type RecordLengthReadCloser struct {

    io.ReadCloser

    length     int

}



func (rc *RecordLengthReadCloser) Read(p []byte) (int, error) {

    n, err := rc.ReadCloser.Read(p)

    rc.length += n

    return n, err

}


func handleHTTP(w http.ResponseWriter, req *http.Request) {

    rc := &RecordLengthReadCloser{ReadCloser: req.Body}

    req.Body = rc

    resp, err := http.DefaultTransport.RoundTrip(req)

    fmt.Println(rc.length)

    _, _ = resp, err

}

這可能有我不知道的問題,我不確定你是否可以自由地重新分配 req.Body 沒有問題。


查看完整回答
反對 回復 2022-07-18
?
人到中年有點甜

TA貢獻1895條經驗 獲得超7個贊

http.Request.Body是類型io.ReadCloser。它是一個interface,您可以利用它來用您自己的實現來包裝 Body 值,io.ReadCloser該實現計算從中讀取的字節數。


package main_test


import (

    "fmt"

    "io"

    "io/ioutil"

    "log"

    "net/http"

    "net/http/httptest"

    "strings"

    "testing"

)


func TestRequestLen(t *testing.T) {

    reqBody := "Hello world!"

    resBody := "Hello, client"

    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        fmt.Fprint(w, resBody)

    }))

    defer ts.Close()


    req, err := http.NewRequest(http.MethodGet, ts.URL, strings.NewReader(reqBody))

    if err != nil {

        log.Fatal(err)

    }

    req.Body = &bytesRead{ReadCloser: req.Body}


    res, err := http.DefaultClient.Do(req)

    if err != nil {

        log.Fatal(err)

    }

    greeting, err := ioutil.ReadAll(res.Body)

    res.Body.Close()

    if err != nil {

        log.Fatal(err)

    }


    if want := resBody; string(greeting) != want {

        t.Fatalf("invalid response body %q want %q", string(greeting), want)

    }

    if want := len(reqBody); req.Body.(*bytesRead).total != want {

        t.Fatalf("invalid request length %v want %v", req.Body.(*bytesRead).total, want)

    }

}


type bytesRead struct {

    io.ReadCloser

    total int

}


func (c *bytesRead) Read(p []byte) (n int, err error) {

    n, err = c.ReadCloser.Read(p)

    c.total += n

    return

}


查看完整回答
反對 回復 2022-07-18
  • 2 回答
  • 0 關注
  • 148 瀏覽
慕課專欄
更多

添加回答

了解更多

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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