From 843cf7ab945ee74a3522c8d677de3c31720a7ff3 Mon Sep 17 00:00:00 2001 From: raul Date: Tue, 21 May 2024 10:38:28 +0200 Subject: [PATCH] Improve error handling --- cmd/clientFunc.go | 4 ++-- cmd/serverFunc.go | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/cmd/clientFunc.go b/cmd/clientFunc.go index 3639c36..881978b 100644 --- a/cmd/clientFunc.go +++ b/cmd/clientFunc.go @@ -77,7 +77,7 @@ func getJSON(codPostal string) (s string, err error) { client := &http.Client{} req, err := http.NewRequest("GET", "https://www.aemet.es/xml/municipios/localidad_"+codPostal+".xml", nil) if err != nil { - e := fmt.Errorf("Error occurred pulling data: %v\n", err) + e := fmt.Errorf("Error occurred creating GET request: %v\n", err) return "", e } req.Header.Set("User-Agent", "AEMET-Client/1.0 (https://git.bulgariu.xyz/raul/aemet)") @@ -85,7 +85,7 @@ func getJSON(codPostal string) (s string, err error) { resp, err := client.Do(req) if err != nil { - e := fmt.Errorf("Error occurred pulling data: %v\n", err) + e := fmt.Errorf("Error occurred executing GET request: %v\n", err) return "", e } diff --git a/cmd/serverFunc.go b/cmd/serverFunc.go index bf6d6cf..26c739d 100644 --- a/cmd/serverFunc.go +++ b/cmd/serverFunc.go @@ -34,14 +34,6 @@ func returnWeather(c *gin.Context) { codPostal := c.Param("localidad") numDias := c.Param("dia") - if numDias != "" { - n, err = strconv.Atoi(numDias) - if err != nil { - c.String(http.StatusNotAcceptable, "Invalid day identifier") - return - } - } - isAvailable := false for k := range localidades { if codPostal == k { @@ -67,6 +59,14 @@ func returnWeather(c *gin.Context) { return } + if numDias != "" { + n, err = strconv.Atoi(numDias) + if err != nil || n > len(aemetRequest.Base.Prediccion.Dia)-1 || n < 0 { + c.String(http.StatusNotAcceptable, "Invalid day identifier") + return + } + } + if numDias != "" { c.IndentedJSON(http.StatusOK, aemetRequest.Base.Prediccion.Dia[n]) } else {