How to write a response (type Response) in a Conn in GO?

huangapple go评论104阅读模式
英文:

How to write a response (type Response) in a Conn in GO?

问题

你好!根据你的代码,你可以使用conn.Write([]byte)方法将响应发送给客户端。但是,http.Response类型的响应不能直接转换为字节。你需要将响应的主体、状态和标头分别提取出来,然后将它们转换为字节并发送给客户端。

这里是一个示例代码,展示了如何将响应发送给客户端:

  1. // 提取响应的主体
  2. body, err := ioutil.ReadAll(resp.Body)
  3. if err != nil {
  4. log.Fatalln(err.Error())
  5. }
  6. // 提取响应的状态码
  7. status := resp.StatusCode
  8. // 提取响应的标头
  9. headers := resp.Header
  10. // 将主体、状态码和标头转换为字节
  11. bodyBytes := []byte(body)
  12. statusBytes := []byte(strconv.Itoa(status))
  13. headerBytes := []byte(headers)
  14. // 发送响应给客户端
  15. conn.Write(statusBytes)
  16. conn.Write(headerBytes)
  17. conn.Write(bodyBytes)

请注意,这只是一个示例代码,你可能需要根据你的实际需求进行适当的修改。希望对你有帮助!如果你有任何其他问题,请随时问我。

英文:

I'm making a webserver in go and I need to give the response form the website to the client.
this in the part of my code where i receive the response:

  1. client := http.Client{}
  2. resp, err := client.Do(request)
  3. defer resp.Body.Close()
  4. if err != nil {
  5. log.Fatalln(err.Error())
  6. }

The Do(request) returns a Response type and I need to send this response to the client (conn). I saw a method in conn type the writes data in the connection but it only accept bytes and i couldn't convert the response in bytes. I need to send the body, status and headers,can the conn.Write([]bytes) do that? How can I send this response to my client?

答案1

得分: 1

http.Response具有一个Write方法,它将响应的内容以HTTP/1.X格式写入到io.Writer中。

这将原样写入响应中的所有内容,因此您可能需要首先删除/修改标头以满足您的需求。

  1. err = resp.Write(conn)
英文:

The http.Response has a Write method, which writes the contents of the response to an io.Writer in HTTP/1.X format.

This will write everything in the response verbatim, so you may need to remove/modify headers first to suit your needs.

  1. err = resp.Write(conn)

huangapple
  • 本文由 发表于 2017年1月11日 02:16:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41575634.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定