尝试使用大猩猩库连接到Websocket时发生运行时错误

时间:2019-12-11 22:11:58

标签: go websocket gorilla

我正在使用Gorilla Websocket,但是出现此错误,它是在尝试从本地主机访问websocket页面后发生的

在尝试访问该页面时也给出ERR_EMPTY_RESPONSE

如果需要更多信息,请告诉我,这是我第一次发布:)

错误

2019/12/11 16:41:35 Client Connected...
2019/12/11 16:41:35 http: panic serving [::1]:37714: runtime error: invalid memory address or nil pointer dereference
goroutine 4 [running]:
net/http.(*conn).serve.func1(0xc420018820)
        /opt/go/src/net/http/server.go:1721 +0xd0
panic(0x65f180, 0x7e3280)
        /opt/go/src/runtime/panic.go:489 +0x2cf
github.com/gorilla/websocket.(*Conn).NextReader(0x0, 0xc42008a0f0, 0xc42001a6c0, 0x28, 0x40, 0x28)
        /opt/gopkg/src/github.com/gorilla/websocket/conn.go:971 +0x26
github.com/gorilla/websocket.(*Conn).ReadMessage(0x0, 0xc4200c2680, 0x14, 0x28, 0x40, 0x7ecca0, 0x14)
        /opt/gopkg/src/github.com/gorilla/websocket/conn.go:1064 +0x2f
main.reader(0x0)
        /home/go/api/main2.go:23 +0x40
main.wsEndpoint(0x7c0ec0, 0xc4200e4000, 0xc42000a800)
        /home/go/api/main2.go:45 +0xeb

执行代码

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

func homePage(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home Page")
}

func reader(conn *websocket.Conn) {
    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            log.Println(err)
            return
        }
        log.Println(string(p))

        if err := conn.WriteMessage(messageType, p); err != nil {
            log.Println(err)
        }
    }
}

func wsEndpoint(w http.ResponseWriter, r *http.Request) {

    ws, err := upgrader.Upgrade(w, r, nil)
    if err != nil {
        log.Println(err)
    }

    log.Println("Client Connected...")

    reader(ws)

}

func setupRoutes() {
    http.HandleFunc("/", homePage)
    http.HandleFunc("/ws", wsEndpoint)
}

func main() {
    fmt.Println("Websocket server started")
    setupRoutes()
    log.Fatal(http.ListenAndServe(":8080", nil))
}

0 个答案:

没有答案