From 42a6bd68a70cda4c268aa8b38e00766a9982ad4a Mon Sep 17 00:00:00 2001
From: Andreas Magnarson Nypan <andrenyp@stud.ntnu.no>
Date: Fri, 7 Mar 2025 13:08:40 +0000
Subject: [PATCH] Upload New File

---
 handlers/info.go | 56 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)
 create mode 100644 handlers/info.go

diff --git a/handlers/info.go b/handlers/info.go
new file mode 100644
index 0000000..c5f07f7
--- /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)
+}
-- 
GitLab