Closed
Description
I'm trying to integrate this into my existing app which is using the Gin framework, but I'm unable to establish a connection from the browser. Any ideas how I can get this working?
Server
package main
import (
"context"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
func main() {
router := gin.New()
router.GET("/ws", handler)
router.Run(":7000")
}
func handler(c *gin.Context) {
log.Println("upgrading")
conn, wsErr := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{
InsecureSkipVerify: true,
})
if wsErr != nil {
c.AbortWithError(http.StatusInternalServerError, wsErr)
return
}
defer conn.Close(websocket.StatusInternalError, "Closed unexepetedly")
log.Println("ready")
ctx, cancel := context.WithTimeout(c.Request.Context(), time.Minute)
defer cancel()
ctx = conn.CloseRead(ctx)
tick := time.NewTicker(time.Second * 5)
defer tick.Stop()
for {
select {
case <-ctx.Done():
log.Println("done")
conn.Close(websocket.StatusNormalClosure, "")
return
case <-tick.C:
writeErr := wsjson.Write(ctx, conn, map[string]interface{}{
"msg": "hello",
})
if writeErr != nil {
log.Println(writeErr)
return
}
}
}
}
Client
const ws = new WebSocket('ws://localhost:7000/ws');
ws.onopen = console.log;
ws.onmessage = console.log;
JS Error
WebSocket connection to 'ws://localhost:7000/ws' failed: Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE
Server logs
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)
[GIN-debug] GET /ws --> main.handler (1 handlers)
[GIN-debug] Listening and serving HTTP on :7000
2019/10/25 15:17:49 upgrading
2019/10/25 15:17:49 ready
2019/10/25 15:17:54 done