2024-05-08 09:08:36 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
2024-05-08 09:29:58 +02:00
|
|
|
"encoding/json"
|
2024-05-08 09:08:36 +02:00
|
|
|
"fmt"
|
|
|
|
"github.com/gin-gonic/gin"
|
2024-05-08 09:29:58 +02:00
|
|
|
"net/http"
|
2024-05-08 09:08:36 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2024-05-15 08:35:00 +02:00
|
|
|
listenPort string = "1302"
|
|
|
|
localidades = map[string]string{
|
2024-05-15 12:27:24 +02:00
|
|
|
"valencia": "46250",
|
|
|
|
"madrid": "28079",
|
|
|
|
"barcelona": "08019",
|
2024-05-15 08:35:00 +02:00
|
|
|
}
|
2024-05-08 09:08:36 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func server() {
|
2024-05-08 09:16:05 +02:00
|
|
|
router := gin.Default()
|
2024-05-15 12:27:24 +02:00
|
|
|
router.GET("/api/:localidad", returnWeather)
|
2024-05-08 09:16:05 +02:00
|
|
|
fmt.Printf("Listening on port %v...\n", listenPort)
|
2024-05-08 10:47:41 +02:00
|
|
|
router.Run(":" + listenPort)
|
2024-05-08 09:16:05 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func returnWeather(c *gin.Context) {
|
2024-05-15 12:27:24 +02:00
|
|
|
codPostal := c.Param("localidad")
|
2024-05-15 08:35:00 +02:00
|
|
|
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])
|
2024-05-08 11:14:30 +02:00
|
|
|
if err != nil {
|
|
|
|
e := fmt.Sprint(err)
|
|
|
|
c.String(http.StatusInternalServerError, e)
|
|
|
|
return
|
|
|
|
}
|
2024-05-08 09:29:58 +02:00
|
|
|
textBytes := []byte(jsonData)
|
|
|
|
aemetRequest := root{}
|
2024-05-08 11:14:30 +02:00
|
|
|
err = json.Unmarshal(textBytes, &aemetRequest)
|
2024-05-08 09:29:58 +02:00
|
|
|
if err != nil {
|
2024-05-09 10:07:00 +02:00
|
|
|
e := fmt.Sprintf("Error occurred unmarshalling data: %v\n", err)
|
|
|
|
c.String(http.StatusInternalServerError, e)
|
2024-05-15 12:27:24 +02:00
|
|
|
return
|
2024-05-08 09:29:58 +02:00
|
|
|
}
|
2024-05-08 09:16:05 +02:00
|
|
|
|
2024-05-08 09:29:58 +02:00
|
|
|
c.IndentedJSON(http.StatusOK, aemetRequest)
|
2024-05-15 08:35:00 +02:00
|
|
|
//c.String(http.StatusOK, jsonData)
|
2024-05-08 09:08:36 +02:00
|
|
|
}
|