-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupgraderequest.go
113 lines (89 loc) · 2.46 KB
/
upgraderequest.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package socketify
import (
"fmt"
"github.com/teris-io/shortid"
"net/http"
)
type UpgradeRequest struct {
server *Server
wr http.ResponseWriter
r *http.Request
done chan bool
clientID string
attributes map[string]interface{}
}
func newUpgradeRequest(server *Server, wr http.ResponseWriter, r *http.Request) *UpgradeRequest {
return &UpgradeRequest{
server: server,
wr: wr,
r: r,
attributes: map[string]interface{}{},
done: make(chan bool),
}
}
func (u *UpgradeRequest) SetClientID(clientID string) *UpgradeRequest {
u.clientID = clientID
return u
}
func (u *UpgradeRequest) SetAttribute(key string, val interface{}) *UpgradeRequest {
u.attributes[key] = val
return u
}
func (u *UpgradeRequest) WriteResponse(statusCode int, header http.Header, response []byte) (int, error) {
defer func() {
u.done <- true
}()
u.wr.WriteHeader(statusCode)
for key, values := range header {
for _, value := range values {
u.wr.Header().Add(key, value)
}
}
return u.wr.Write(response)
}
func (u *UpgradeRequest) Request() *http.Request {
return u.r
}
func (u *UpgradeRequest) Upgrade() (*Connection, error) {
defer func() {
u.done <- true
}()
var ef *encryptionFields
if u.server.opts.encryption != nil {
// TODO: Implement Encryption
if u.server.opts.encryption.Method == EncryptionTypeRsaAes && u.server.opts.encryption.rsaAes != nil {
key, err := u.server.parseRsaPublicKey(u.r)
if err != nil {
u.wr.WriteHeader(http.StatusBadRequest)
u.wr.Write([]byte(err.Error()))
u.server.opts.logger.Error("Error parsing rsa public key from connection", err)
return nil, err
}
ef = &encryptionFields{
clientPublicKey: key,
}
serverPrivateKey, err := u.server.opts.encryption.rsaAes.privateKey()
if err != nil {
u.wr.WriteHeader(http.StatusInternalServerError)
u.wr.Write([]byte(err.Error()))
u.server.opts.logger.Error("Error getting server private key", err)
return nil, err
}
ef.serverPrivateKey = serverPrivateKey
}
}
var headers http.Header
c, err := u.server.upgrade.Upgrade(u.wr, u.r, headers)
if err != nil {
u.server.opts.logger.Error("Error upgrading request", err, fmt.Sprintf("Headers: %+v", u.r.Header))
return nil, err
}
if u.clientID == "" {
u.clientID = shortid.MustGenerate()
}
connection := newConnection(u.server, c, u.clientID, ef)
if u.server.storage != nil {
u.server.storage.addClient(connection)
}
return connection, nil
}