-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
82 lines (65 loc) · 1.72 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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"time"
)
const apiUrl = "https://api.open-meteo.com/v1/forecast?latitude=56.8575&longitude=60.6125¤t=temperature_2m"
type ResponseWeather struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
GenerationtimeMS float64 `json:"generationtime_ms"`
UTCOffsetSeconds int64 `json:"utc_offset_seconds"`
Timezone string `json:"timezone"`
TimezoneAbbreviation string `json:"timezone_abbreviation"`
Elevation float64 `json:"elevation"`
CurrentUnits CurrentUnits `json:"current_units"`
Current Current `json:"current"`
}
type Current struct {
Time string `json:"time"`
Interval int64 `json:"interval"`
Temperature2M float64 `json:"temperature_2m"`
}
type CurrentUnits struct {
Time string `json:"time"`
Interval string `json:"interval"`
Temperature2M string `json:"temperature_2m"`
}
var resp ResponseWeather
func init() {
getTemp()
}
func main() {
go func() {
for range time.Tick(60 * time.Second) {
getTemp()
}
}()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
preparedData, jsonErr := json.Marshal(resp.Current.Temperature2M)
if jsonErr != nil {
log.Fatal(jsonErr)
}
w.Header().Set("Content-Type", "application/json")
w.Write(preparedData)
})
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println(err)
}
}
func getTemp() {
data, err := http.Get(apiUrl)
if err != nil {
getTemp()
}
defer data.Body.Close()
body, err := io.ReadAll(data.Body)
if err != nil {
log.Fatal(err)
}
json.Unmarshal(body, &resp)
}