-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
128 lines (107 loc) · 2.54 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
120
121
122
123
124
125
126
127
128
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
"github.com/fatih/color"
"github.com/joho/godotenv"
)
// Weather structure
type Weather struct {
Location struct {
Name string `json:"name"`
Country string `json:"country"`
Region string `json:"region"`
} `json:"location"`
Current struct {
TempC float64 `json:"temp_c"`
Condition struct {
Text string `json:"text"`
} `json:"condition"`
} `json:"current"`
Forecast struct {
Forecastday []struct {
Hour []struct {
TimeEpoch int `json:"time_epoch"`
TempC float64 `json:"temp_c"`
Condition struct {
Text string `json:"text"`
} `json:"condition"`
ChanceOfRain float64 `json:"chance_of_rain"`
} `json:"hour"`
} `json:"forecastday"`
} `json:"forecast"`
}
func main() {
// Load env file
err := godotenv.Load()
if err != nil {
panic(err)
}
// Get env file
rapidAPIKey := os.Getenv("RAPID_API_KEY")
rapidAPIHost := os.Getenv("RAPID_API_HOST")
q := "Denpasar"
if len(os.Args) >= 2 {
q = os.Args[1]
}
url := "https://weatherapi-com.p.rapidapi.com/forecast.json?q=" + q + "&days=3"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
panic(err)
}
req.Header.Add("X-RapidAPI-Key", rapidAPIKey)
req.Header.Add("X-RapidAPI-Host", rapidAPIHost)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
if res.StatusCode != 200 {
panic("API call failed with " + res.Status)
} else {
fmt.Println("API call succeeded with " + res.Status)
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
panic(err)
}
// fmt.Println(string(body))
var weather Weather
err = json.Unmarshal(body, &weather)
if err != nil {
panic(err)
}
location, curerrent, hours := weather.Location, weather.Current, weather.Forecast.Forecastday[0].Hour
fmt.Printf("Weather Forecast for %s, %s (%s): %.0fC, %s\n\n",
location.Name,
location.Region,
location.Country,
curerrent.TempC,
curerrent.Condition.Text)
for _, hour := range hours {
date := time.Unix(int64(hour.TimeEpoch), 0)
// Time now & future
if date.Before(time.Now()) {
continue
}
message := fmt.Sprintf(
"Time: %s \nTemp: %.0fC, %s \nChance of rain %.0f%% \n\n",
date.Format("15:04"),
hour.TempC,
hour.Condition.Text,
hour.ChanceOfRain,
)
if hour.ChanceOfRain < 40 {
color.Green(message)
} else if hour.ChanceOfRain >= 40 && hour.ChanceOfRain <= 70 {
color.Yellow(message)
} else {
color.Red(message)
}
}
}