-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice.go
87 lines (76 loc) · 2.01 KB
/
service.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
// +build linux darwin
package main
import (
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
// "bytes"
"time"
// "github.com/takama/daemon"
)
func getLogFilePath() string {
return "/var/log/myservice.log"
}
func acceptConnection(listener net.Listener, listen chan<- net.Conn) {
for {
conn, err := listener.Accept()
if err != nil {
continue
}
listen <- conn
}
}
func handleClient(client net.Conn) {
for {
buf := make([]byte, 4096)
numbytes, err := client.Read(buf)
fmt.Printf("numbytes: %d, err: %s, buf: %v \r\n", numbytes, err, buf[:numbytes])
if numbytes == 0 || err != nil {
// EOF, close connection
return
}
if numbytes == 2 && buf[0] == 13 && buf[1] == 10 {
// [13 10] "\r\n"
} else {
now := time.Now()
str := fmt.Sprintf("%s: %s\r\n", now.Local().Format("15:04:05.999999999"), buf)
client.Write([]byte(str))
}
}
}
func runService(name string, idDebug bool) (string, error) {
log.Println("runService()\r\n")
// Set up channel on which to send signal notifications.
// We must use a buffered channel or risk missing the signal
// if we're not ready to receive when the signal is sent.
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, os.Kill, syscall.SIGTERM)
// Set up listener for defined host and port
listener, err := net.Listen("tcp", port)
if err != nil {
return "Possibly was a problem with the port binding", err
}
// set up channel on which to send accepted connections
listen := make(chan net.Conn, 100)
go acceptConnection(listener, listen)
// loop work cycle with accept connections or interrupt
// by system signal
log.Println("Manage() loop\r\n")
for {
select {
case conn := <-listen:
go handleClient(conn)
case killSignal := <-interrupt:
log.Println("Got signal:", killSignal, "\r\n")
log.Println("Stoping listening on ", listener.Addr(), "\r\n")
listener.Close()
if killSignal == os.Interrupt {
return "Daemon was interruped by system signal", nil
}
return "Daemon was killed", nil
}
}
}