Skip to content
Snippets Groups Projects
Commit 42a6bd68 authored by Andreas Magnarson Nypan's avatar Andreas Magnarson Nypan
Browse files

Upload New File

parent 20985187
No related branches found
No related tags found
No related merge requests found
Pipeline #30875 canceled
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)
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment