gpt4 book ai didi

go - 我想在 golang 中使用劫持,同时在客户端上得到无效响应

转载 作者:数据小太阳 更新时间:2023-10-29 03:36:29 25 4
gpt4 key购买 nike

我想在 golang 中使用劫持,同时在客户端收到无效响应

func hijack(w http.ResponseWriter, r *http.Request) {
fmt.Println("start")

hj, ok := w.(http.Hijacker)

fmt.Println(ok)

c, buf, err := hj.Hijack()
if err != nil {
panic(err)
}
n, err := buf.Write([]byte("hello"))
if err != nil {
panic(err)
}

fmt.Println("n == ",n)

err = buf.Flush()
if err != nil {
panic(err)
}

fmt.Println("end")
}

服务器上打印如下:

start

true

n == 5

end

但我在客户端出现以下错误

localhost sent an invalid response. ERR_INVALID_HTTP_RESPONSE

最佳答案

正如劫机者的文档所说

Hijack lets the caller take over the connection. After a call to Hijack the HTTP server library will not do anything else with the connection.
It becomes the caller's responsibility to manage and close the connection.
The returned net.Conn may have read or write deadlines already set, depending on the configuration of the Server. It is the caller's responsibility to set or clear those deadlines as needed.
The returned bufio.Reader may contain unprocessed buffered data from the client.
After a call to Hijack, the original Request.Body must not be used. The original Request's Context remains valid and is not canceled until the Request's ServeHTTP method returns.

您需要写入c 而不是buf。并且您需要编写响应状态和 Content-Length header 。

http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Println("start")

writer.Header().Add("Content-Length", "5")
writer.WriteHeader(200)
hj, ok := writer.(http.Hijacker)

fmt.Println(ok)

c, _, err := hj.Hijack()
if err != nil {
panic(err)
}
n, err := c.Write([]byte("hello"))
if err != nil {
panic(err)
}

fmt.Println("n == ",n)

err = c.Close()
if err != nil {
panic(err)
}

fmt.Println("end")
})

关于go - 我想在 golang 中使用劫持,同时在客户端上得到无效响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54403928/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com