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

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

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

问题

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

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

// 提取响应的主体
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    log.Fatalln(err.Error())
}

// 提取响应的状态码
status := resp.StatusCode

// 提取响应的标头
headers := resp.Header

// 将主体、状态码和标头转换为字节
bodyBytes := []byte(body)
statusBytes := []byte(strconv.Itoa(status))
headerBytes := []byte(headers)

// 发送响应给客户端
conn.Write(statusBytes)
conn.Write(headerBytes)
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:

            client := http.Client{}
			resp, err := client.Do(request)
			defer resp.Body.Close()

			if err != nil {
				log.Fatalln(err.Error())
			}

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中。

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

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.

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:

确定