响应未实现http.Hijacker [英] Response does not implement http.Hijacker

查看:295
本文介绍了响应未实现http.Hijacker的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Go并尝试在我的项目中实现WebSocket.在执行此操作时.我收到"WebSocket:响应未实现HTTP.Hijacker".错误.我是这项技术的新手.谁能帮我解决这个问题?

I'm using Go and trying to implement WebSocket in my project. while implementing this. I get "WebSocket: response does not implement HTTP.Hijacker" error. I'm new to this technology. Can anyone help me resolve this?

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")
} 

推荐答案

该应用程序正在使用中间件";包装了net/http服务器的 ResponseWriter 实现.中间件包装程序未实现 Hijacker 接口.

The application is using "middleware" that wraps the net/http server's ResponseWriter implementation. The middleware wrapper does not implement the Hijacker interface.

此问题有两个解决方法:

There are two fixes for the problem:

  • 删除有问题的中间件.

  • Remove the offending middleware.

通过委派给基础响应来在中间件包装器上实现Hijacker接口.该方法的实现将如下所示:

Implement the Hijacker interface on the middleware wrapper by delegating through to the underlying response. The method implementation will look something like this:

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()
}

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

If you don't know what the response writer wrapper is, add a statement to print the type from the handler:

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

这篇关于响应未实现http.Hijacker的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆