-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
109 lines (86 loc) · 2.19 KB
/
app.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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strconv"
"github.com/joho/godotenv"
)
type HostNameIPStatus struct {
IP string
Status bool
}
type GetHostNameResponse struct {
Result []string `json:"result"`
Status string `json:"status"`
Error error `json:"error"`
}
var ipMap map[string][]HostNameIPStatus
func main() {
err := loadMockData()
if err != nil {
log.Fatal("Failed to load mock data: ", err)
}
http.HandleFunc("/mta-hosting-optimizer", getInstanceName)
log.Fatal(http.ListenAndServe(":8999", nil))
}
func getInstanceName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
thresholdEnv := GoDotEnvVariable("X")
// thresholdEnv := getEnv("X","1")
threshold, err := strconv.Atoi(thresholdEnv)
if err != nil {
log.Println("Error converting string to int")
json.NewEncoder(w).Encode(GetHostNameResponse{
Result: nil,
Status: "Error",
Error: err,
})
return
}
result := getInefficientInstance(threshold)
json.NewEncoder(w).Encode(result)
}
func getInefficientInstance(threshold int) []string {
InefficientInstance := make([]string, 0)
for key, val := range ipMap {
count := 0
for _, ipStatus := range val {
if ipStatus.Status {
count++
}
}
if count <= threshold {
InefficientInstance = append(InefficientInstance, key)
}
}
return InefficientInstance
}
func loadMockData() error {
ips := []string{"127.0.0.1", "127.0.0.2", "127.0.0.3", "127.0.0.4", "127.0.0.5", "127.0.0.6"}
hostNames := []string{"mta-prod-1", "mta-prod-1", "mta-prod-2", "mta-prod-2", "mta-prod-2", "mta-prod-3"}
actives := []bool{true, false, true, true, false, false}
ipMap = make(map[string][]HostNameIPStatus)
for idx := 0; idx < len(ips); idx++ {
ipMap[hostNames[idx]] = append(ipMap[hostNames[idx]], HostNameIPStatus{
IP: ips[idx],
Status: actives[idx],
})
}
return nil
}
func getEnv(key string, defaultValue string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return defaultValue
}
func GoDotEnvVariable(key string) string {
// load .env file
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file")
}
return os.Getenv(key)
}