响应没有实现 http.Hijacker

Yuv*_*mar 3 go websocket gorilla

我正在使用 Go 并尝试在我的项目中实现 WebSocket。在实现这一点的同时。我收到“WebSocket:响应没有实现 HTTP.Hijacker”错误。我是这项技术的新手。谁能帮我解决这个问题?

var upgrader = websocket.Upgrader{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
} 

func HandleConnections(w http.ResponseWriter, r *http.Request) {
    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println("err", err)
        return
    }

    log.Println("hello client")
} 
Run Code Online (Sandbox Code Playgroud)

Cer*_*món 7

该应用程序正在使用包装 net/http 服务器的ResponseWriter实现的“中间件” 。中间件包装器没有实现Hijacker接口。

该问题有两个修复方法:

  • 删除有问题的中间件。

  • 通过委托给底层响应,在中间件包装器上实现 Hijacker 接口。方法实现将如下所示:

    func (w *wrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) {
        h, ok := w.underlyingResponseWriter.(http.Hijacker)
        if !ok {
            return nil, nil, errors.New("hijack not supported")
        }
        return h.Hijack()
    }
    
    Run Code Online (Sandbox Code Playgroud)

如果您不知道响应编写器包装器是什么,请添加一条语句以从处理程序打印类型:

func HandleConnections(w http.ResponseWriter, r *http.Request) {
    fmt.Printf("w's type is %T\n", w)
    ...
Run Code Online (Sandbox Code Playgroud)


kos*_*tix 0

引用以下文档http.Hijacker

~$ go doc http.Hijacker

package http // import "net/http"

type Hijacker interface {
  // 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.
  Hijack() (net.Conn, *bufio.ReadWriter, error)
}
Run Code Online (Sandbox Code Playgroud)

Hijacker接口的实现ResponseWriters允许 HTTP 处理程序接管连接。

ResponseWriterHTTP/1.x 连接默认支持Hijacker,但 HTTP/2 连接故意不支持。 ResponseWriter包装器也可能不支持Hijacker. 处理程序应始终在运行时测试此功能。

所以,我看到你的问题发生的几种可能性:

  • 您正在尝试将 HTTP/2 连接转换为 Websocket。
  • 您正在使用一些“中间件”,它包装库存net/http包传递给处理程序的任何对象,就像net/http.ResponseWriter不费心实现正确Hijack方法来支持net/http.Hijacker接口的东西一样。