-
Notifications
You must be signed in to change notification settings - Fork 0
/
observer.go
147 lines (113 loc) · 2.21 KB
/
observer.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const monitoring = 4
const delay = 5
func main() {
showIntro()
for {
showMenu()
command := readCommand()
switch command {
case 1:
startMonitoring()
case 2:
showLogs()
case 0:
fmt.Println("Exiting")
os.Exit(0)
default:
fmt.Println("Unknown command")
os.Exit(-1)
}
}
}
func showIntro() {
username := "Alan"
version := 1.0
fmt.Println("Hello, sr.", username)
fmt.Println("This application is at version:", version)
}
func showMenu() {
fmt.Println("1- Start Monitoring")
fmt.Println("2- Show Logs")
fmt.Println("0- Exit")
}
func readCommand() int {
var command int
fmt.Scan(&command)
fmt.Println("")
return command
}
func startMonitoring() {
fmt.Println("Monitoring...")
apps := readApps()
for i := 0; i < monitoring; i++ {
for i, app := range apps {
fmt.Println("Testing application", i, ":", app)
testApp(app)
}
time.Sleep(delay * time.Second)
fmt.Println("")
}
fmt.Println("")
}
func testApp(app string) {
res, err := http.Get(app)
if err != nil {
fmt.Println("Error:", err)
return
}
if res.StatusCode == 200 {
fmt.Println("Application:", app, "was successfully loaded!")
registryLog(app, true)
} else {
fmt.Println("Application:", app, "is having problems. Status code:", res.StatusCode)
registryLog(app, false)
}
}
func readApps() []string {
var apps []string
file, err := os.Open("apps.txt")
if err != nil {
fmt.Println("Error:", err)
return nil
}
reader := bufio.NewReader(file)
for {
line, err := reader.ReadString('\n')
line = strings.TrimSpace(line)
apps = append(apps, line)
if err == io.EOF {
break
}
}
file.Close()
return apps
}
func registryLog(app string, status bool) {
file, err := os.OpenFile("log.txt", os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
fmt.Println("Error:", err)
return
}
file.WriteString(time.Now().Format("02/01/2006 15:04:05") + " - " + app + " - online: " + strconv.FormatBool(status) + "\n")
file.Close()
}
func showLogs() {
file, err := ioutil.ReadFile("log.txt")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(file))
}