英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论