Select Git revision
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
infohandler.go 3.66 KiB
package handelers
import(
"strings"
"net/http"
"fmt"
"strconv"
"encoding/json"
)
// Henter landdata fra REST Countries API
func getCountryDataByCode(countryCode string) (*CountryInfo, error) {
url := fmt.Sprintf("http://129.241.150.113:8080/v3.1/alpha/%s", countryCode)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error retrieving country data, status code: %d", resp.StatusCode)
}
var countries []CountryInfo
if err := json.NewDecoder(resp.Body).Decode(&countries); err != nil {
return nil, err
}
if len(countries) == 0 {
return nil, fmt.Errorf("country not found for code: %s", countryCode)
}
return &countries[0], nil
}
func CountryInfoHandler(w http.ResponseWriter, r *http.Request) {
parts := strings.Split(r.URL.Path, "/")
if len(parts) < 5 {
http.Error(w, "Invalid format. Use: /countryinfo/v1/info/{countryCode}", http.StatusBadRequest)
return
}
countryCode := parts[4]
// Hent landdata fra REST Countries API
country, err := getCountryDataByCode(countryCode)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Hent antall byer som skal vises fra URL-parameteren (default til 10)
// F.eks. /countryinfo/v1/info/NO?cities=5
cityCount := 10 // Standardverdi
cityCountStr := r.URL.Query().Get("cities") // Hent "cities" parameteren
if cityCountStr != "" {
// Prøv å konvertere parameteren til et heltall
if count, err := strconv.Atoi(cityCountStr); err == nil && count > 0 {
cityCount = count
}
}
// Hent byene fra countriesnow API
cities, err := getCitiesByCountry(country.Name.Common)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Hvis det er flere enn det brukeren ønsker, begrens listen
if len(cities) > cityCount {
cities = cities[:cityCount]
}
// Feilsøking: Hvis ingen byer ble funnet
if len(cities) == 0 {
fmt.Printf("No cities found for %s\n", country.Name.Common)
}
// Bygg kombinert respons
response := CombinedInfo{
Name: country.Name.Common,
Continents: country.Continents,
Population: country.Population,
Languages: country.Languages,
Borders: country.Borders,
Flags: country.Flags.PNG,
Capital: "",
Cities: strings.Join(cities, ", "), // Legg til de 10 første byene som en kommaseparert liste
}
if len(country.Capital) > 0 {
response.Capital = country.Capital[0]
}
// Sett Content-Type til application/json
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func getCitiesByCountry(countryName string) ([]string, error) {
url := fmt.Sprintf("https://countriesnow.space/api/v0.1/countries/cities/q?country=%s", countryName)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error retrieving cities, status code: %d", resp.StatusCode)
}
var responseBody map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&responseBody); err != nil {
return nil, err
}
if cities, ok := responseBody["data"].([]interface{}); ok {
var cityList []string
for _, city := range cities {
if cityStr, ok := city.(string); ok {
cityList = append(cityList, cityStr)
}
}
// Hvis ingen byer er funnet, returner en feilmelding
if len(cityList) == 0 {
fmt.Println("No cities found in the response.")
}
return cityList, nil
}
return nil, fmt.Errorf("no cities found for country %s", countryName)
}