DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 3b11cab50c793375f1e7fd13a83c2ccaf9917f04 deck-builder/.archived/sdbapi/handlers/ws.go -rw-r--r-- 1.2 KiB
3b11cab5Jonni Liljamo chore(api): chrono and uuid deps 1 year, 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
 * 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
			}
		}
	}()
}