forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
websocket.go
72 lines (56 loc) · 1.54 KB
/
websocket.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
package operations
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
"github.com/lxc/lxd/lxd/response"
"github.com/lxc/lxd/shared"
)
type operationWebSocket struct {
req *http.Request
op *Operation
}
// OperationWebSocket returns a new websocket operation.
func OperationWebSocket(req *http.Request, op *Operation) response.Response {
return &operationWebSocket{req, op}
}
func (r *operationWebSocket) Render(w http.ResponseWriter) error {
chanErr, err := r.op.Connect(r.req, w)
if err != nil {
return err
}
err = <-chanErr
return err
}
func (r *operationWebSocket) String() string {
_, md, err := r.op.Render()
if err != nil {
return fmt.Sprintf("error: %s", err)
}
return md.ID
}
type forwardedOperationWebSocket struct {
req *http.Request
id string
source *websocket.Conn // Connection to the node were the operation is running
}
// ForwardedOperationWebSocket returns a new forwarted websocket operation.
func ForwardedOperationWebSocket(req *http.Request, id string, source *websocket.Conn) response.Response {
return &forwardedOperationWebSocket{req, id, source}
}
func (r *forwardedOperationWebSocket) Render(w http.ResponseWriter) error {
// Upgrade target connection to websocket.
target, err := shared.WebsocketUpgrader.Upgrade(w, r.req, nil)
if err != nil {
return err
}
// Start proxying between sockets.
<-shared.WebsocketProxy(r.source, target)
// Make sure both sides are closed.
r.source.Close()
target.Close()
return nil
}
func (r *forwardedOperationWebSocket) String() string {
return r.id
}