Fetch basic weather info from AEMET

This commit is contained in:
raul 2024-05-03 09:24:00 +02:00
parent dcf0a88710
commit 947c3c0c43
1 changed files with 41 additions and 1 deletions

42
main.go
View File

@ -1,17 +1,51 @@
package main package main
import ( import (
"encoding/json"
"fmt" "fmt"
xj "github.com/basgys/goxml2json"
"io" "io"
"log" "log"
"net/http" "net/http"
"strings"
) )
type root struct {
Base struct {
Nombre string `json:"nombre"`
Prediccion struct {
Dia []struct {
Fecha string `json:"-fecha"`
Temperatura struct {
Maxima string `json:"maxima"`
Minima string `json:"minima"`
}
}
}
} `json:"root"`
}
func main() { func main() {
jsonData := getJSON()
textBytes := []byte(jsonData)
aemetRequest := root{}
err := json.Unmarshal(textBytes, &aemetRequest)
if err != nil {
log.Fatalf("Error occurred unmarshalling data: %v\n", err)
}
fmt.Println(aemetRequest.Base.Nombre)
fmt.Println(aemetRequest.Base.Prediccion.Dia[0].Fecha)
fmt.Println(aemetRequest.Base.Prediccion.Dia[0].Temperatura.Maxima)
fmt.Println(aemetRequest.Base.Prediccion.Dia[0].Temperatura.Minima)
}
func getJSON() string {
resp, err := http.Get("https://www.aemet.es/xml/municipios/localidad_46250.xml") resp, err := http.Get("https://www.aemet.es/xml/municipios/localidad_46250.xml")
if err != nil { if err != nil {
log.Fatalf("Error occurred pulling data: %v\n", err) log.Fatalf("Error occurred pulling data: %v\n", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
log.Fatalf("Error occurred accessing website: %v\n", err) log.Fatalf("Error occurred accessing website: %v\n", err)
@ -22,5 +56,11 @@ func main() {
log.Fatalf("Error occurred reading data: %v\n", err) log.Fatalf("Error occurred reading data: %v\n", err)
} }
fmt.Print(string(data)) xml := strings.NewReader(string(data))
json, err := xj.Convert(xml)
if err != nil {
log.Fatalf("Error occurred converting XML to JSON: %v\n", err)
}
return json.String()
} }