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

Upload New File

parent 8691e33e
No related branches found
No related tags found
No related merge requests found
Pipeline #30879 canceled
package utils
import (
"CountryAPI/models"
"encoding/json"
"fmt"
"log"
"math"
"net/http"
"strings"
)
// fetching the country data using the alpha code to find the my country
func FetchCountryData(countryCode string) (models.CountryInfoStruct, error) {
url := "http://129.241.150.113:8080/v3.1/alpha/" + countryCode
r, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
fmt.Errorf("Error in creating request:", err.Error())
}
client := &http.Client{}
res, err := client.Do(r)
if err != nil {
fmt.Errorf("Error in response:", err.Error())
}
decoder := json.NewDecoder(res.Body)
var countryAPI []map[string]any
if err := decoder.Decode(&countryAPI); err != nil {
log.Fatal(err)
}
country := countryAPI[0]
//countryname
name := ""
if nameData, ok := country["name"].(map[string]any); ok {
name, _ = nameData["common"].(string)
}
//continent
var continents []string // for all the arrays with strings i do this to extract my strings
if continentData, ok := country["continents"].([]any); ok {
for _, v := range continentData {
if con, ok := v.(string); ok {
continents = append(continents, con)
}
}
}
// population
population := int(country["population"].(float64))
var languages []string
if langList, ok := country["languages"].(map[string]any); ok {
for _, v := range langList {
if lan, ok := v.(string); ok {
languages = append(languages, lan)
}
}
}
//borders
var borders []string
if borderData, ok := country["borders"].([]any); ok {
for _, v := range borderData {
if bor, ok := v.(string); ok {
borders = append(borders, bor)
}
}
}
//flag
var flag string
if flagData, ok := country["flags"].(map[string]any); ok {
flag, _ = flagData["png"].(string)
}
//capital
var capital string
if capitalData, ok := country["capital"].([]any); ok && len(capitalData) > 0 {
if cap, ok := capitalData[0].(string); ok {
capital = cap
}
}
return models.CountryInfoStruct{
Name: name,
Continents: continents,
Population: population,
Languages: languages,
Borders: borders,
Flag: flag,
Capital: capital,
}, nil
}
// fetching cities
func FetchCities(countryName string) ([]string, error) {
url := "http://129.241.150.113:3500/api/v0.1/countries/cities"
rb := `{"country":"` + countryName + `"}`
r, err := http.NewRequest(http.MethodPost, url, strings.NewReader(rb))
if err != nil {
fmt.Errorf("Error in creating request:", err.Error())
}
r.Header.Set("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(r)
if err != nil {
fmt.Errorf("Error in creating response:", err.Error())
}
var citiesData struct {
Data []string `json:"data"`
}
if err := json.NewDecoder(res.Body).Decode(&citiesData); err != nil {
log.Fatal(err)
}
return citiesData.Data, nil
}
// fetching population data
func FetchPopulationData(countryCode string, startYear, endYear int) (map[string]any, error) {
//Using fetchcountrydata to find the country name cus cant use iso2 directrly to look at population stats
countryData, err := FetchCountryData(countryCode)
if err != nil {
return nil, fmt.Errorf("error fetching country name:", err)
}
countryName := countryData.Name
url := "http://129.241.150.113:3500/api/v0.1/countries/population"
rb := `{"country":"` + countryName + `"}`
r, err := http.NewRequest(http.MethodPost, url, strings.NewReader(rb))
if err != nil {
return nil, fmt.Errorf("error creating request:", err)
}
r.Header.Set("Content-Type", "application/json")
client := &http.Client{}
res, err := client.Do(r)
if err != nil {
return nil, fmt.Errorf("error creating response:", err)
}
//i did the whole because of alot error checking previously
var popData struct {
Error bool `json:"error"`
Msg string `json:"msg"`
Data struct {
Country string `json:"country"`
Code string `json:"code"`
Iso3 string `json:"iso3"`
PopulationCounts []struct {
Year int `json:"year"`
Value int `json:"value"`
} `json:"populationCounts"`
} `json:"data"`
}
if err := json.NewDecoder(res.Body).Decode(&popData); err != nil {
return nil, fmt.Errorf("error decoding JSON: %w", err)
}
var filteredValues []map[string]int
var totalPopulation, count int
for _, record := range popData.Data.PopulationCounts {
if (startYear == 0 || record.Year >= startYear) && (endYear == 0 || record.Year <= endYear) {
filteredValues = append(filteredValues, map[string]int{
"year": record.Year,
"value": record.Value,
})
totalPopulation += record.Value
count++
}
}
meanPopulation := 0
if count > 0 {
meanPopulation = int(math.Round(float64(totalPopulation) / float64(count))) // findding the means
}
return map[string]interface{}{
"mean": meanPopulation,
"values": filteredValues,
}, nil
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment