From 68690d25c0fcbb647d397e513fa5b48752f3d9e0 Mon Sep 17 00:00:00 2001 From: Mathilde Hertaas <maimh@stud.ntnu.no> Date: Fri, 28 Feb 2025 12:12:27 +0100 Subject: [PATCH] all information is now availible in the info endpoint except cities --- main.go | 143 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 72 insertions(+), 71 deletions(-) diff --git a/main.go b/main.go index e50c9e5..85cd6ed 100644 --- a/main.go +++ b/main.go @@ -7,129 +7,130 @@ import ( "strings" ) -//countryinfo/v1/info/{country_code}{?limit=10} - //given country, 2-letter country codes (ISO 3166-2). - //limit is the number of cities that are listed in the response. +type Flags struct{ + PNG string `json:"png"` +} -// Struktur for å lagre data om landene i info endepunktet +// Struktur for data fra REST Countries API type CountryInfo struct { Name struct { - Common string `json:"common"` - Official string `json:"official"` - } `json:"name"` - Capital []string `json:"capital"` - Region string `json:"region"` + Common string `json:"common"` + Official string `json:"official"` + } `json:"name"` + Capital []string `json:"capital"` Languages map[string]string `json:"languages"` + Continents []string `json:"continents"` + Borders []string `json:"borders"` + Population int `json:"population"` + Flags Flags `json:"flags"` + Cities []string `json:"cities"` } -//Når du kjører koden blir du sendt til en hjemmeside siden forespørsel spesifikasjoner ikke er gitt enda - //info om hvordan bruke API - func homeHandler(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - // Strukturert respons for bedre lesbarhet - response := map[string]interface{}{ - "WELCOME": "Welcome to the Country Info API", - "endpoints": map[string]interface{}{ - "Endpoint 1": map[string]string{ - "Description": "Get information about a country using its ISO 3166-1 alpha-2 code.", - "URL": "http://localhost:8080/countryinfo/v1/info/{country_code}{?limit=10}", - "Example": "http://localhost:8080/countryinfo/v1/info/NO", - }, - "Endpoint 2": map[string]interface{}{ - "Description": "TO BE IMPLEMENTED", - - }, - - }, - } - - json.NewEncoder(w).Encode(response) - } - +// Struktur for kombinert respons +type CombinedInfo struct { + Name string `json:"name"` + Continents []string `json:"continenents"` + Population int `json:"population"` + Languages map[string]string `json:"languages"` + Borders []string `json:"borders"` + Flags string `json:"flags"` + Capital string `json:"capital"` + Cities string `json:"cities"` +} -// En funksjon som henter data fra det eksterne API-et ved landkode +// Henter landdata fra REST Countries API func getCountryDataByCode(countryCode string) (*CountryInfo, error) { - - //bygge en URL for API kallet url := fmt.Sprintf("http://129.241.150.113:8080/v3.1/alpha/%s", countryCode) - - //sender en http forespørsel resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() - - // Sjekk om API-kallet var vellykket (statuskode 200) if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("error retrieving country data, status code: %d", resp.StatusCode) } - // Håndterer en http feil, som om landet ikke finnes var countries []CountryInfo if err := json.NewDecoder(resp.Body).Decode(&countries); err != nil { return nil, err } - // Hvis vi ikke får noen treff if len(countries) == 0 { return nil, fmt.Errorf("country not found for code: %s", countryCode) } - // Returner det første elementet i listen siden forventer bare ett treff) return &countries[0], nil } -//oprett en handler for /countryinfo/v1/info/{country_code} -// leser landkoden fra URL -// slår opp dataene -// REturnerer dem som JSON -func handler(w http.ResponseWriter, r *http.Request) { - // Hent landkode fra path +// Handler som kombinerer data fra begge API-er +func countryInfoHandler(w http.ResponseWriter, r *http.Request) { parts := strings.Split(r.URL.Path, "/") if len(parts) < 5 { - http.Error(w, "Invalid format. Please use the format /countryinfo/v1/info/{countryCode}{?limit=10}. Example: /countryinfo/v1/info/NO", http.StatusBadRequest) + http.Error(w, "Invalid format. Use: /countryinfo/v1/info/{countryCode}", http.StatusBadRequest) return } - countryCode := parts[4] // Landkoden er den 5. delen av pathen (fra 0) + countryCode := parts[4] - // Hent data fra API ved landkode - //country inneholder data om alt går bra + // Hent data fra begge API-er country, err := getCountryDataByCode(countryCode) - //err inneholder feil hvis noe går galt, ikke finner landkode if err != nil { - http.Error(w, fmt.Sprintf( - "Error retrieving data for country code: %s. Check if the country code is correct.\nExample: /countryinfo/v1/info/NO\nError: %s", - countryCode, err.Error(), - ), http.StatusInternalServerError) + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + + + // 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: "", } + if len(country.Capital) > 0 { + response.Capital = country.Capital[0] + } + + if len(country.Cities) > 0 { + response.Cities = country.Cities[0] + } + - // Returner JSON-respons w.Header().Set("Content-Type", "application/json") - json.NewEncoder(w).Encode(country) + json.NewEncoder(w).Encode(response) } - -// kaller de ulike funkjsonene basert på hvilken URL som sender forespørsel func main() { + http.HandleFunc("/", homeHandler) + http.HandleFunc("/countryinfo/v1/info/", countryInfoHandler) - http.HandleFunc("/",homeHandler) - //Rute for info om land - http.HandleFunc("/countryinfo/v1/info/", handler) - - //info i terminal fmt.Println("Server running on port 8080...") - if err := http.ListenAndServe(":8080", nil); err != nil { - // Logg feilen og avslutt programmet dersom serveren ikke kan starte fmt.Printf("Server failed to start: %s\n", err) } } -//URL for å teste info for norge -//http://localhost:8080/countryinfo/v1/info/No \ No newline at end of file +func homeHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + response := map[string]interface{}{ + "WELCOME": "Welcome to the Country Info API", + "endpoints": map[string]interface{}{ + "Get Country Info": map[string]string{ + "Description": "Get country details including cities, population, and more.", + "URL": "http://localhost:8080/countryinfo/v1/info/{country_code}", + "Example": "http://localhost:8080/countryinfo/v1/info/NO", + }, + }, + } + + json.NewEncoder(w).Encode(response) +} -- GitLab