forked from cerdrifix/gofair
/
connection.go
55 lines (41 loc) · 1016 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
55
package streaming
import (
"bufio"
"crypto/tls"
"github.com/Bl4cksunLtd/gofair/streaming/models"
)
type tlsConnection struct {
ID int32
conn *tls.Conn
}
func (conn *tlsConnection) Write(b []byte) (int, error) {
return conn.conn.Write(b)
}
func (conn *tlsConnection) Stop() {
conn.conn.Close()
conn.conn = nil
}
func newTLSConnection(destination string, certs *tls.Certificate) (*tlsConnection, error) {
connection := new(tlsConnection)
cfg := &tls.Config{Certificates: []tls.Certificate{*certs}}
conn, err := tls.Dial("tcp", destination, cfg)
if err != nil {
return nil, err
}
reader := bufio.NewReader(conn)
buf, _, err := reader.ReadLine()
if err != nil {
return nil, err
}
connectionMessage := new(models.ConnectionMessage)
err = connectionMessage.UnmarshalJSON(buf)
if err != nil {
return nil, err
}
// Check we have a valid connection ID
if connectionMessage.ConnectionID == "" {
return nil, &ConnectionError{}
}
connection.conn = conn
return connection, nil
}