File: websocket.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (82 lines) | stat: -rw-r--r-- 1,791 bytes parent folder | download | duplicates (5)
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
package operations

import (
	"fmt"
	"net/http"

	"github.com/gorilla/websocket"

	"github.com/lxc/incus/v6/internal/server/response"
	"github.com/lxc/incus/v6/shared/ws"
)

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
}

// Code returns the HTTP code.
func (r *operationWebSocket) Code() int {
	return http.StatusOK
}

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 := ws.Upgrader.Upgrade(w, r.req, nil)
	if err != nil {
		return err
	}

	// Start proxying between sockets.
	<-ws.Proxy(r.source, target)

	// Make sure both sides are closed.
	_ = r.source.Close()
	_ = target.Close()

	return nil
}

func (r *forwardedOperationWebSocket) String() string {
	return r.id
}

// Code returns the HTTP code.
func (r *forwardedOperationWebSocket) Code() int {
	return http.StatusOK
}