Add requesting weather from individual days

This commit is contained in:
raul 2024-05-21 09:22:19 +02:00
parent a8cb384800
commit faad6a72fb
1 changed files with 25 additions and 3 deletions

View File

@ -3,8 +3,10 @@ package cmd
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/gin-gonic/gin"
"net/http" "net/http"
"strconv"
"github.com/gin-gonic/gin"
) )
var ( var (
@ -17,14 +19,29 @@ var (
) )
func server() { func server() {
//gin.SetMode(gin.ReleaseMode)
router := gin.Default() router := gin.Default()
router.GET("/api/:localidad", returnWeather) router.GET("/api/:localidad", returnWeather)
router.GET("/api/:localidad/:dia", returnWeather)
fmt.Printf("Listening on port %v...\n", listenPort) fmt.Printf("Listening on port %v...\n", listenPort)
router.Run(":" + listenPort) router.Run(":" + listenPort)
} }
func returnWeather(c *gin.Context) { func returnWeather(c *gin.Context) {
c.Writer.Header().Set("Federal-Agents", "Outside my home")
var n int
var err error
codPostal := c.Param("localidad") 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 isAvailable := false
for k := range localidades { for k := range localidades {
if codPostal == k { if codPostal == k {
@ -32,7 +49,7 @@ func returnWeather(c *gin.Context) {
} }
} }
if isAvailable == false { if isAvailable == false {
c.String(http.StatusNotFound, "The locality doesn't exist or is currently not supported\n") c.String(http.StatusNotFound, "The locality doesn't exist or is currently not supported, sorry\n")
return return
} }
jsonData, err := getJSON(localidades[codPostal]) jsonData, err := getJSON(localidades[codPostal])
@ -50,6 +67,11 @@ func returnWeather(c *gin.Context) {
return return
} }
c.IndentedJSON(http.StatusOK, aemetRequest) if numDias != "" {
c.IndentedJSON(http.StatusOK, aemetRequest.Base.Prediccion.Dia[n])
} else {
c.IndentedJSON(http.StatusOK, aemetRequest)
}
//c.JSON(http.StatusOK, aemetRequest)
//c.String(http.StatusOK, jsonData) //c.String(http.StatusOK, jsonData)
} }