-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
77 lines (55 loc) · 1.4 KB
/
server.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
package draftTerm
import (
"github.com/kr/pty"
"golang.org/x/net/websocket"
"os/exec"
"fmt"
)
type terminalServer struct {
command string
arguments []string
}
//
// Create new instance of TerminalServer
//
func NewTerminalServer(pCommand string, pArguments ...string) *terminalServer {
return &terminalServer{ command: pCommand,arguments: []string(pArguments)}
}
func killCommand(pCommand *exec.Cmd) {
if (pCommand.Process == nil) {
return
}
err:=pCommand.Process.Kill()
if err != nil {
logError("Failed to kill command",err)
}
_,err=pCommand.Process.Wait()
if err != nil {
logError("Failed to wait command",err)
return
}
}
//
// WebSocket Handler
// it execute the command and manage i/o trough the pty for each websocket connection
func (self *terminalServer) Handler(ws *websocket.Conn) {
logMessage(fmt.Sprintf("Opened connection from %v ",ws.Request().RemoteAddr))
defer ws.Close()
vCmd := exec.Command(self.command, self.arguments...)
defer killCommand(vCmd)
vStdinPipe, err := pty.Start(vCmd)
defer vStdinPipe.Close()
if err != nil {
logError("Failed to start command in the pty",err)
return
}
vSyncChannel:=make(chan bool,1)
go pipe(vStdinPipe, ws, vSyncChannel)
vInputChannel:= NewInputChannel(ws,vStdinPipe)
for {
vErr:=vInputChannel.ProcessIncomingMessage(vSyncChannel)
if vErr != nil {
return
}
}
}