-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (90 loc) · 1.98 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
package main
import (
"encoding/json"
"fmt"
"html/template"
"log"
"math/rand"
"net/http"
"os"
"time"
)
type Status struct {
Water int `json:"water"`
Wind int `json:"wind"`
}
type Data struct {
Status `json:"status"`
}
type Condition struct {
Water string
Wind string
}
type Response struct {
Status
Condition
}
func updateData() {
for {
var data = Data{Status: Status{}}
maxValue := 20
data.Status.Water = rand.Intn(maxValue)
data.Status.Wind = rand.Intn(maxValue)
b, err := json.MarshalIndent(&data, "", " ")
if err != nil {
log.Fatalln("error while marshalling json data =>", err.Error())
}
err = os.WriteFile("data.json", b, 0644)
if err != nil {
log.Fatalln("error while writing value to data.json file =>", err.Error())
}
fmt.Println("menggungu 5 detik")
time.Sleep(time.Second * 5)
}
}
func main() {
rand.Seed(time.Now().UnixNano())
go updateData()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
tpl, _ := template.ParseFiles("index.html")
var data = Data{Status: Status{}}
b, err := os.ReadFile("data.json")
if err != nil {
fmt.Fprint(w, "error")
return
}
if err = json.Unmarshal(b, &data); err != nil {
fmt.Fprint(w, "error")
return
}
response := Response{Status: data.Status}
response.Condition.Water = generateWaterStatus(data.Status.Water)
response.Condition.Wind = generateWindStatus(data.Status.Wind)
tpl.ExecuteTemplate(w, "index.html", response)
})
http.ListenAndServe("127.0.0.1:8080", nil)
}
func generateWaterStatus(status int) string {
waterStatus := ""
switch {
case status <= 6:
waterStatus = "Safe"
case status > 6 && status <= 9:
waterStatus = "Standby"
case status > 9:
waterStatus = "Danger"
}
return waterStatus
}
func generateWindStatus(status int) string {
windStatus := ""
switch {
case status <= 6:
windStatus = "Safe"
case status > 6 && status <= 15:
windStatus = "Standby"
case status > 15:
windStatus = "Danger"
}
return windStatus
}