aemet/cmd/serverFunc.go

54 lines
1.1 KiB
Go

package cmd
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
var (
listenPort string = "1302"
localidades = map[string]string{
"valencia": "46250",
"madrid": "28079",
}
)
func server() {
router := gin.Default()
router.GET("/api/:codigopostal", returnWeather)
fmt.Printf("Listening on port %v...\n", listenPort)
router.Run(":" + listenPort)
}
func returnWeather(c *gin.Context) {
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)
return
}
textBytes := []byte(jsonData)
aemetRequest := root{}
err = json.Unmarshal(textBytes, &aemetRequest)
if err != nil {
e := fmt.Sprintf("Error occurred unmarshalling data: %v\n", err)
c.String(http.StatusInternalServerError, e)
}
c.IndentedJSON(http.StatusOK, aemetRequest)
//c.String(http.StatusOK, jsonData)
}