/*
* This file is part of sdbapi
* Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
*
* Licensed under GPL-3.0-only.
* See LICENSE for licensing information.
*/
package handlers
import (
"io"
"log"
"github.com/gin-gonic/gin"
"github.com/gobwas/ws"
"github.com/gobwas/ws/wsutil"
)
func WS(c *gin.Context) {
// upgrade connection to ws
conn, _, _, err := ws.UpgradeHTTP(c.Request, c.Writer)
if err != nil {
log.Printf("got err when upgrading http request, err: %q", err)
}
go func() {
defer conn.Close()
var (
state = ws.StateServerSide
reader = wsutil.NewReader(conn, state)
writer = wsutil.NewWriter(conn, state, ws.OpText)
//decoder = json.NewDecoder(reader)
//encoder = json.NewEncoder(writer)
)
for {
header, err := reader.NextFrame()
if err != nil {
log.Printf("ws header err: %q", err)
return
}
if header.OpCode == ws.OpClose {
log.Printf("ws client disconnect")
return
}
// set right opcode for writer
writer.Reset(conn, state, header.OpCode)
if _, err = io.Copy(writer, reader); err != nil {
log.Printf("copy err: %q", err)
return
}
if err = writer.Flush(); err != nil {
log.Printf("flush err: %q", err)
return
}
}
}()
}