package cmd import ( "encoding/json" "fmt" "net/http" "strconv" "github.com/gin-gonic/gin" ) var ( listenPort string = "1302" localidades = map[string]string{ "valencia": "46250", "madrid": "28079", "barcelona": "08019", } ) func server() { //gin.SetMode(gin.ReleaseMode) router := gin.Default() router.GET("/api/:localidad", returnWeather) router.GET("/api/:localidad/:dia", returnWeather) fmt.Printf("Listening on port %v...\n", listenPort) router.Run(":" + listenPort) } func returnWeather(c *gin.Context) { c.Writer.Header().Set("Federal-Agents", "Outside my home") var n int var err error codPostal := c.Param("localidad") numDias := c.Param("dia") 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, sorry\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) 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 { c.IndentedJSON(http.StatusOK, aemetRequest) } //c.JSON(http.StatusOK, aemetRequest) //c.String(http.StatusOK, jsonData) }