Use dictionaries for requesting locality weather

This is the first time in my life I've found a practical use for
dictionaries myself
This commit is contained in:
raul 2024-05-15 08:35:00 +02:00
parent 281e194bc5
commit e70106932d
2 changed files with 21 additions and 5 deletions

View File

@ -58,9 +58,9 @@ type root struct {
// fmt.Printf("Temperatura mínima: %v°C\n", aemetRequest.Base.Prediccion.Dia[0].Temperatura.Minima)
// }
func getJSON() (s string, err error) {
func getJSON(codPostal string) (s string, err error) {
client := &http.Client{}
req, err := http.NewRequest("GET", "https://www.aemet.es/xml/municipios/localidad_46250.xml", nil)
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)
return "", e

View File

@ -9,17 +9,32 @@ import (
var (
listenPort string = "1302"
localidades = map[string]string{
"valencia": "46250",
"madrid": "28079",
}
)
func server() {
router := gin.Default()
router.GET("/api/valencia", returnWeather)
router.GET("/api/:codigopostal", returnWeather)
fmt.Printf("Listening on port %v...\n", listenPort)
router.Run(":" + listenPort)
}
func returnWeather(c *gin.Context) {
jsonData, err := getJSON()
codPostal := c.Param("codigopostal")
isAvailable := false
for k := range localidades {
if codPostal == k {
isAvailable = true
}
}
if isAvailable == false {
c.String(http.StatusNotFound, "The locality doesn't exist or is currently not supported\n")
return
}
jsonData, err := getJSON(localidades[codPostal])
if err != nil {
e := fmt.Sprint(err)
c.String(http.StatusInternalServerError, e)
@ -34,4 +49,5 @@ func returnWeather(c *gin.Context) {
}
c.IndentedJSON(http.StatusOK, aemetRequest)
//c.String(http.StatusOK, jsonData)
}