转换。对字节数组的响应

我正在尝试开发一个tcp代理,在这个tcp代理中,我将不得不操纵http和tcp请求。


目前,对于传入的请求,我检测它是http还是tcp请求,如果它是http,那么我将其解析为: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)

    // 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

}

但是,我找不到将响应转换回字节或字符串数组的方法,我是否遗漏了某些内容?


慕婉清6462132
浏览 156回答 1
1回答

芜湖不芜

一个网址。请求对象具有 Write 方法:func (r *Request) Write(w io.Writer) error写入以有线格式写入 HTTP/1.1 请求,即标头和正文。您可以使用它将字节写入缓冲区对象。例如:package mainimport (&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "net/http")func main() {&nbsp; &nbsp; var buf bytes.Buffer&nbsp; &nbsp; req, err := http.NewRequest("GET", "http://google.com", nil)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; client := &http.Client{}&nbsp; &nbsp; res, err := client.Do(req)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer res.Body.Close()&nbsp; &nbsp; if err := res.Write(&buf); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; // ...do whatever you want with the buffer here...&nbsp; &nbsp; fmt.Println(buf.String())}Buffer 对象具有 Bytes 方法,该方法将返回一个字节数组(如果需要)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go