aemet/main.go

67 lines
1.5 KiB
Go
Raw Normal View History

2024-04-29 08:58:30 +02:00
package main
import (
2024-05-03 09:24:00 +02:00
"encoding/json"
2024-04-29 08:58:30 +02:00
"fmt"
2024-05-03 09:24:00 +02:00
xj "github.com/basgys/goxml2json"
2024-04-29 08:58:30 +02:00
"io"
"log"
"net/http"
2024-05-03 09:24:00 +02:00
"strings"
2024-04-29 08:58:30 +02:00
)
2024-05-03 09:24:00 +02:00
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"`
}
2024-04-29 08:58:30 +02:00
func main() {
2024-05-03 09:24:00 +02:00
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)
2024-05-05 12:46:07 +02:00
fmt.Printf("Temperatura máxima: %v°C\n", aemetRequest.Base.Prediccion.Dia[0].Temperatura.Maxima)
fmt.Printf("Temperatura mínima: %v°C\n", aemetRequest.Base.Prediccion.Dia[0].Temperatura.Minima)
2024-05-03 09:24:00 +02:00
}
func getJSON() string {
2024-04-29 08:58:30 +02:00
resp, err := http.Get("https://www.aemet.es/xml/municipios/localidad_46250.xml")
if err != nil {
log.Fatalf("Error occurred pulling data: %v\n", err)
}
2024-05-03 09:24:00 +02:00
2024-04-29 08:58:30 +02:00
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
log.Fatalf("Error occurred accessing website: %v\n", err)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error occurred reading data: %v\n", err)
}
2024-05-03 09:24:00 +02:00
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()
2024-04-29 08:58:30 +02:00
}