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

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

轉換。對字節數組的響應

轉換。對字節數組的響應

Go
慕婉清6462132 2022-09-26 19:58:15
我正在嘗試開發一個tcp代理,在這個tcp代理中,我將不得不操縱http和tcp請求。目前,對于傳入的請求,我檢測它是http還是tcp請求,如果它是http,那么我將其解析為:http.Requestfunc (s *TcpProxy) OnMessage(c *connection.Connection, ctx interface{}, data []byte) interface{} {    reader := bytes.NewReader(data)    newReader := bufio.NewReader(reader)    req, err := http.ReadRequest(newReader)    // This is an http request}現在,我方便地操作請求,因為我可以使用從該接口公開的方法,然后最終我將響應從我的代理發送回接收入站請求的服務。func (s *TcpProxy) OnMessage(c *connection.Connection, ctx interface{}, data []byte) interface{} {    reader := bytes.NewReader(data)    newReader := bufio.NewReader(reader)    req, err := http.ReadRequest(newReader)    // Manipulate http request    // ...    // Proxy the request    proxyReq, err := http.NewRequest(req.Method, proxyUrl, req.Body)    // Capture the duration while making a request to the destination service.    res, err := httpClient.Do(proxyReq)        buf := res.ToBuffer() // <= How can I achieve this       c.Send(buf)    c.Close()    return nil}但是,我找不到將響應轉換回字節或字符串數組的方法,我是否遺漏了某些內容?
查看完整描述

1 回答

?
蕪湖不蕪

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

一個網址。請求對象具有 Write 方法:


func (r *Request) Write(w io.Writer) error

寫入以有線格式寫入 HTTP/1.1 請求,即標頭和正文。


您可以使用它將字節寫入緩沖區對象。例如:


package main


import (

    "bytes"

    "fmt"

    "net/http"

)


func main() {

    var buf bytes.Buffer


    req, err := http.NewRequest("GET", "http://google.com", nil)

    if err != nil {

        panic(err)

    }


    client := &http.Client{}

    res, err := client.Do(req)

    if err != nil {

        panic(err)

    }

    defer res.Body.Close()


    if err := res.Write(&buf); err != nil {

        panic(err)

    }


    // ...do whatever you want with the buffer here...

    fmt.Println(buf.String())

}

Buffer 對象具有 Bytes 方法,該方法將返回一個字節數組(如果需要)。


查看完整回答
反對 回復 2022-09-26
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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