-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
119 lines (100 loc) · 2.49 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
117
118
119
package main
import (
"bytes"
"encoding/csv"
"fmt"
"os"
"time"
"github.com/joho/godotenv"
)
func loadEnvVariables() {
err := godotenv.Load(".env")
if err != nil {
fmt.Println("Error loading .env file")
panic(err)
}
}
var AREAS = []string{
"Eagle River",
"Kincaid Park",
"Far North Bicentennial Park",
"Bear Valley",
"Fire Island",
}
func main() {
loadEnvVariables()
requester := GetAreaRequester(AREAS)
requester.passInformationIfFreshData()
for {
time.Sleep(time.Second * 5)
if requester.passInformationIfFreshData() {
break
}
}
for {
timeBefore := time.Now().UnixMilli()
requester.passInformationIfFreshData()
timeAfter := time.Now().UnixMilli()
timeTaken := timeAfter - timeBefore
timeToSleep := 1800*1000 - timeTaken
time.Sleep(time.Millisecond * time.Duration(timeToSleep))
}
}
func (responses RequestResponse) IsSuccessful() bool {
return responses.err == nil && responses.statusCode == 200
}
func (requester AreaRequester) passInformationIfFreshData() bool {
// FETCH DATA FROM API
responses := requester.RequestAreas()
fmt.Println("Attempt to pass information at " + time.Now().Format("2006-01-02 15:04:05"))
var containsAnyDifferentData = false
// COMPARE DATA TO DATA IN FILES
for _, response := range responses {
if !response.IsSuccessful() {
continue
}
// COMPARE DATA TO DATA IN FILES
data, err := os.ReadFile(getFilePath(response.area, "csv"))
if err != nil {
containsAnyDifferentData = true
break
}
if !bytes.Equal(data, response.data) {
fmt.Println("diff")
containsAnyDifferentData = true
break
}
}
if !containsAnyDifferentData {
return false
}
fmt.Println("Pass information to API")
// IF DATA IS NEW, DO REQUEST
for _, response := range responses {
go requester.attemptInformationPass(response)
}
return true
}
func (requester AreaRequester) attemptInformationPass(response RequestResponse) {
area := response.area
data := response.data
writeRawCSVFile(data, area)
reader := csv.NewReader(bytes.NewBuffer(data))
rows, err := reader.ReadAll()
if err != nil {
fmt.Println("Error converting to csv file for " + area)
return
}
weatherData := CSVWeatherData(rows, area)
weatherDataRequest, statusCode, err := requester.PostAreaData(weatherData)
if err != nil {
fmt.Println("Error posting data for " + area)
return
}
fmt.Print("completed ")
fmt.Print(string(area))
fmt.Print(" request with status code ")
fmt.Print(statusCode)
fmt.Print(" and data ")
fmt.Println(string(weatherDataRequest))
}