-
Notifications
You must be signed in to change notification settings - Fork 3
/
console.go
99 lines (88 loc) · 2.17 KB
/
console.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
// -*- coding: utf-8 -*-
// Package helloworld provides a set of Cloud Functions samples.
package main
import (
//"encoding/json"
"fmt"
"io"
"net"
"strings"
//"bytes"
//"net/http"
//"strconv"
// "context"
"bufio"
"log"
)
func StartConsole(hostInfo HostInfo) {
server := hostInfo.toStr()
log.Print("start console --- ", server)
local, err := net.Listen("tcp", server)
if err != nil {
log.Fatal(err)
}
defer local.Close()
for {
conn, err := local.Accept()
if err != nil {
log.Fatal(err)
}
log.Print("console connected")
go func(stream net.Conn) {
defer stream.Close()
ConsoleService(stream)
}(conn)
}
}
type CMD struct {
name string
description string
proc func(args []string, scanner *bufio.Scanner, ostream io.Writer) bool
}
var cmdList = []CMD{}
func init() {
cmdList = append(cmdList, CMD{"info", "print information", printInformation})
cmdList = append(cmdList, CMD{"chat", "start chat", startChat})
cmdList = append(cmdList, CMD{"help", "print help", printHelp})
cmdList = append(cmdList, CMD{"exit", "eixt console", exitConsole})
}
func printInformation(args []string, scanner *bufio.Scanner, ostream io.Writer) bool {
DumpSession(ostream)
return true
}
func startChat(args []string, scanner *bufio.Scanner, ostream io.Writer) bool {
return true
}
func printHelp(args []string, scanner *bufio.Scanner, ostream io.Writer) bool {
ostream.Write([]byte("command list:\n"))
for _, cmd := range cmdList {
ostream.Write([]byte(fmt.Sprintf(" %s: %s\n", cmd.name, cmd.description)))
}
return true
}
func exitConsole(args []string, scanner *bufio.Scanner, ostream io.Writer) bool {
return false
}
func ConsoleService(stream io.ReadWriteCloser) {
scanner := bufio.NewScanner(stream)
name2CMD := map[string]CMD{}
for _, cmd := range cmdList {
name2CMD[cmd.name] = cmd
}
stream.Write([]byte("tunnel> "))
for scanner.Scan() {
args := strings.Split(scanner.Text(), " \t")
if len(args) > 0 {
if cmd, has := name2CMD[args[0]]; has {
if !cmd.proc(args, scanner, stream) {
break
}
} else {
printHelp(args, scanner, stream)
}
} else {
printHelp(args, scanner, stream)
}
stream.Write([]byte("tunnel> "))
}
}