Main project #1
|
@ -25,11 +25,14 @@ type root struct {
|
|||
} `json:"root"`
|
||||
}
|
||||
|
||||
func main() {
|
||||
jsonData := getJSON()
|
||||
func client() {
|
||||
jsonData, err := getJSON()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
textBytes := []byte(jsonData)
|
||||
aemetRequest := root{}
|
||||
err := json.Unmarshal(textBytes, &aemetRequest)
|
||||
err = json.Unmarshal(textBytes, &aemetRequest)
|
||||
if err != nil {
|
||||
log.Fatalf("Error occurred unmarshalling data: %v\n", err)
|
||||
}
|
||||
|
@ -40,27 +43,40 @@ func main() {
|
|||
fmt.Printf("Temperatura mínima: %v°C\n", aemetRequest.Base.Prediccion.Dia[0].Temperatura.Minima)
|
||||
}
|
||||
|
||||
func getJSON() string {
|
||||
resp, err := http.Get("https://www.aemet.es/xml/municipios/localidad_46250.xml")
|
||||
func getJSON() (s string, err error) {
|
||||
client := &http.Client{}
|
||||
req, err := http.NewRequest("GET", "https://www.aemet.es/xml/municipios/localidad_46250.xml", nil)
|
||||
if err != nil {
|
||||
log.Fatalf("Error occurred pulling data: %v\n", err)
|
||||
e := fmt.Errorf("Error occurred pulling data: %v\n", err)
|
||||
return "", e
|
||||
}
|
||||
req.Header.Set("User-Agent", "AEMET-Client/1.0 (https://git.bulgariu.xyz/raul/aemet)")
|
||||
|
||||
resp, err := client.Do(req)
|
||||
|
||||
if err != nil {
|
||||
e := fmt.Errorf("Error occurred pulling data: %v\n", err)
|
||||
return "", e
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
log.Fatalf("Error occurred accessing website: %v\n", err)
|
||||
e := fmt.Errorf("Error occurred accessing upstream website: %v\n", resp.Status)
|
||||
return "", e
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Fatalf("Error occurred reading data: %v\n", err)
|
||||
e := fmt.Errorf("Error occurred reading data: %v\n", err)
|
||||
return "", e
|
||||
}
|
||||
|
||||
xml := strings.NewReader(string(data))
|
||||
json, err := xj.Convert(xml)
|
||||
if err != nil {
|
||||
log.Fatalf("Error occurred converting XML to JSON: %v\n", err)
|
||||
e := fmt.Errorf("Error occurred converting XML to JSON: %v\n", err)
|
||||
return "", e
|
||||
}
|
||||
|
||||
return json.String()
|
||||
return json.String(), nil
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue