diff --git a/handlers/info.go b/handlers/info.go new file mode 100644 index 0000000000000000000000000000000000000000..c5f07f7c26a23fd302903e03c10ec79c534eadb4 --- /dev/null +++ b/handlers/info.go @@ -0,0 +1,56 @@ +package handlers + +import ( + "CountryAPI/models" + "CountryAPI/utils" + "encoding/json" + "net/http" + "strconv" + "strings" +) + +func HandleCountryInfo(rw http.ResponseWriter, r *http.Request) { + pathParts := strings.Split(r.URL.Path, "/") + countryCode := pathParts[len(pathParts)-1] + limit := 0 + myQuery := r.URL.Query() + limitString := myQuery.Get("limit") + if limitString != "" { + limitTest, err := strconv.Atoi(limitString) // converting it to int + if err == nil { + limit = limitTest + } + } + + //fetching the countrydata + countryData, err := utils.FetchCountryData(countryCode) + if err != nil { + http.Error(rw, "Error fetching country data.", http.StatusInternalServerError) + } + + //cities is fetched seperate using the country name from previous fetch + cityData, err := utils.FetchCities(countryData.Name) + if err != nil { + http.Error(rw, "Error fetching city data", http.StatusInternalServerError) + } + + //If a limit is given cut the city data + if limit > 0 && limit < len(cityData) { + cityData = cityData[:limit] + } + + endpoint := models.CountryInfoStruct{ + Name: countryData.Name, + Continents: countryData.Continents, + Population: countryData.Population, + Languages: countryData.Languages, + Borders: countryData.Borders, + Flag: countryData.Flag, + Capital: countryData.Capital, + Cities: cityData, + } + + rw.Header().Set("Content-Type", "application/json") + + json.NewEncoder(rw).Encode(endpoint) +}