-
-
Notifications
You must be signed in to change notification settings - Fork 86
/
connection.go
54 lines (45 loc) · 1014 Bytes
/
connection.go
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
package main
import (
"errors"
"fmt"
"net"
"sync"
"github.com/gorilla/websocket"
"github.com/zorchenhimer/MovieNight/common"
)
type chatConnection struct {
*websocket.Conn
mutex sync.RWMutex
forwardedFor string
clientName string
}
func (cc *chatConnection) ReadData(data interface{}) error {
cc.mutex.RLock()
defer cc.mutex.RUnlock()
stats.msgInInc()
return cc.ReadJSON(data)
}
func (cc *chatConnection) WriteData(data interface{}) error {
cc.mutex.Lock()
defer cc.mutex.Unlock()
stats.msgOutInc()
err := cc.WriteJSON(data)
if err != nil {
var opErr *net.OpError
if errors.As(err, &opErr) {
common.LogDebugf("OpError: %v\n", opErr)
}
return fmt.Errorf("Error writing data to %s %s: %w", cc.clientName, cc.Host(), err)
}
return nil
}
func (cc *chatConnection) Host() string {
if len(cc.forwardedFor) > 0 {
return cc.forwardedFor
}
host, _, err := net.SplitHostPort(cc.RemoteAddr().String())
if err != nil {
return cc.RemoteAddr().String()
}
return host
}