-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
73 lines (53 loc) · 1.6 KB
/
main.go
File metadata and controls
73 lines (53 loc) · 1.6 KB
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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
)
type Location struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
func getLocation(city string) (lat float64, lon float64, err error) {
response, err := http.Get("http://api.openweathermap.org/geo/1.0/direct?q=" + city + "&limit=1&appid=" + os.Getenv("OPENWEATHER_API_KEY"))
if err != nil {
fmt.Println("Something went wrong while getting the response:", err)
return
}
// Make sure to close the response body
defer response.Body.Close()
var locations []Location
if err := json.NewDecoder(response.Body).Decode(&locations); err != nil {
fmt.Println("Something went wrong while decoding the response body:", err)
return 0, 0, err
}
return locations[0].Lat, locations[0].Lon, nil
}
func main() {
allArgs := os.Args
if len(allArgs) < 2 {
fmt.Println("Please provide a city name")
return
}
city := allArgs[1]
lat, lon, err := getLocation(city)
if err != nil {
fmt.Println("Something went wrong while getting the location:", err)
return
}
weatherResponse, err := http.Get("https://api.openweathermap.org/data/3.0/onecall?lat=" + strconv.FormatFloat(lat, 'f', -1, 64) + "&lon=" + strconv.FormatFloat(lon, 'f', -1, 64) + "&appid=" + os.Getenv("OPENWEATHER_API_KEY"))
if err != nil {
fmt.Println("Something went wrong while getting the weather:", err)
return
}
defer weatherResponse.Body.Close()
weather, err := io.ReadAll(weatherResponse.Body)
if err != nil {
fmt.Println("Something went wrong while reading the weather:", err)
return
}
fmt.Println("Weather:", string(weather))
}