/
connect.go
57 lines (46 loc) · 1.25 KB
/
connect.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
package service
import (
"fmt"
"io"
"net"
"net/http"
"net/http/httputil"
"github.com/deviceplane/controller/pkg/agent/server/conncontext"
"github.com/deviceplane/controller/pkg/codes"
"github.com/deviceplane/controller/pkg/utils"
)
func (s *Service) connectTCP(w http.ResponseWriter, r *http.Request) {
withPort(w, r, func(port int) {
conn := conncontext.GetConn(r)
localConn, err := net.Dial("tcp", fmt.Sprintf(":%d", port))
if err != nil {
println(err.Error())
http.Error(w, err.Error(), codes.StatusDeviceConnectionFailure)
return
}
go io.Copy(localConn, conn)
io.Copy(conn, localConn)
})
}
func (s *Service) connectHTTP(w http.ResponseWriter, r *http.Request) {
withPort(w, r, func(port int) {
conn := conncontext.GetConn(r)
serverConn := httputil.NewServerConn(conn, nil)
req, err := serverConn.Read()
if err != nil {
println(err.Error())
http.Error(w, err.Error(), codes.StatusDeviceConnectionFailure)
return
}
req.RequestURI = ""
req.URL.Scheme = "http"
req.URL.Host = fmt.Sprintf("localhost:%d", port)
resp, err := http.DefaultClient.Do(req)
if err != nil {
println(err.Error())
http.Error(w, err.Error(), codes.StatusDeviceConnectionFailure)
return
}
utils.ProxyResponse(w, resp)
})
}