-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
116 lines (89 loc) · 2.14 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/* ThreadedEchoServer
*/
package main
import (
"net"
"os"
// "os/exec"
"syscall"
"time"
"fmt"
"encoding/json"
"code.google.com/p/goconf/conf"
)
type NostraRequest struct {
Version string
Params []string
}
func main() {
c, err := conf.ReadConfigFile("nostra.conf")
checkError(err)
port, err := c.GetString("default", "port")
service := ":" + port
tcpAddr, err := net.ResolveTCPAddr("ip4", service)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
continue
}
go handleClient(conn)
}
}
func handleClient(conn net.Conn) {
defer conn.Close()
var buf [512]byte
for {
n, err := conn.Read(buf[0:])
if err != nil {
return
}
var request NostraRequest
json.Unmarshal(buf[0:n], &request)
if request.Version == "" || len(request.Params) == 0 {
conn.Write([]byte("{\"code\":-1,\"data\":{\"message\":\"Malformed input\"}}"))
return
}
ret := "{\"code\":0,\"data\":{"
for _, param := range(request.Params) {
switch param {
case "hostname":
// cmd := exec.Command("hostname")
// output, err := cmd.Output()
// hostname := (string(output)[:len(output) - 1])
hostname, err := os.Hostname()
if err != nil {
conn.Write([]byte("{\"code\":-2,\"data\":{\"message\":\"Server derped\"}}"))
return
} else {
ret += "\"hostname\":\"" + hostname + "\","
}
case "time":
time := time.Now().Format(time.RFC3339)
ret += "\"time\":\"" + time + "\","
case "uptime":
var info syscall.Sysinfo_t
err := syscall.Sysinfo(&info)
if err != nil {
return
}
return
default:
conn.Write([]byte("{\"code\":-3,\"data\":{\"message\":\"Unknown parameter (" + param + ")\"}}"))
return
}
}
ret = ret[:len(ret) - 1]
ret += "}}"
conn.Write([]byte(ret))
return
}
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}