Skip to content
Snippets Groups Projects
Commit 68690d25 authored by Mathilde Hertaas's avatar Mathilde Hertaas
Browse files

all information is now availible in the info endpoint except cities

parent 06a502b9
No related branches found
No related tags found
No related merge requests found
...@@ -7,129 +7,130 @@ import ( ...@@ -7,129 +7,130 @@ import (
"strings" "strings"
) )
//countryinfo/v1/info/{country_code}{?limit=10} type Flags struct{
//given country, 2-letter country codes (ISO 3166-2). PNG string `json:"png"`
//limit is the number of cities that are listed in the response. }
// Struktur for å lagre data om landene i info endepunktet // Struktur for data fra REST Countries API
type CountryInfo struct { type CountryInfo struct {
Name struct { Name struct {
Common string `json:"common"` Common string `json:"common"`
Official string `json:"official"` Official string `json:"official"`
} `json:"name"` } `json:"name"`
Capital []string `json:"capital"` Capital []string `json:"capital"`
Region string `json:"region"`
Languages map[string]string `json:"languages"` 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 // Struktur for kombinert respons
//info om hvordan bruke API type CombinedInfo struct {
func homeHandler(w http.ResponseWriter, r *http.Request) { Name string `json:"name"`
w.Header().Set("Content-Type", "application/json") Continents []string `json:"continenents"`
// Strukturert respons for bedre lesbarhet Population int `json:"population"`
response := map[string]interface{}{ Languages map[string]string `json:"languages"`
"WELCOME": "Welcome to the Country Info API", Borders []string `json:"borders"`
"endpoints": map[string]interface{}{ Flags string `json:"flags"`
"Endpoint 1": map[string]string{ Capital string `json:"capital"`
"Description": "Get information about a country using its ISO 3166-1 alpha-2 code.", Cities string `json:"cities"`
"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)
} }
// Henter landdata fra REST Countries API
// En funksjon som henter data fra det eksterne API-et ved landkode
func getCountryDataByCode(countryCode string) (*CountryInfo, error) { 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) url := fmt.Sprintf("http://129.241.150.113:8080/v3.1/alpha/%s", countryCode)
//sender en http forespørsel
resp, err := http.Get(url) resp, err := http.Get(url)
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer resp.Body.Close()
// Sjekk om API-kallet var vellykket (statuskode 200)
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("error retrieving country data, status code: %d", resp.StatusCode) 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 var countries []CountryInfo
if err := json.NewDecoder(resp.Body).Decode(&countries); err != nil { if err := json.NewDecoder(resp.Body).Decode(&countries); err != nil {
return nil, err return nil, err
} }
// Hvis vi ikke får noen treff
if len(countries) == 0 { if len(countries) == 0 {
return nil, fmt.Errorf("country not found for code: %s", countryCode) 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 return &countries[0], nil
} }
//oprett en handler for /countryinfo/v1/info/{country_code} // Handler som kombinerer data fra begge API-er
// leser landkoden fra URL func countryInfoHandler(w http.ResponseWriter, r *http.Request) {
// slår opp dataene
// REturnerer dem som JSON
func handler(w http.ResponseWriter, r *http.Request) {
// Hent landkode fra path
parts := strings.Split(r.URL.Path, "/") parts := strings.Split(r.URL.Path, "/")
if len(parts) < 5 { 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 return
} }
countryCode := parts[4] // Landkoden er den 5. delen av pathen (fra 0) countryCode := parts[4]
// Hent data fra API ved landkode // Hent data fra begge API-er
//country inneholder data om alt går bra
country, err := getCountryDataByCode(countryCode) country, err := getCountryDataByCode(countryCode)
//err inneholder feil hvis noe går galt, ikke finner landkode
if err != nil { if err != nil {
http.Error(w, fmt.Sprintf( http.Error(w, err.Error(), http.StatusInternalServerError)
"Error retrieving data for country code: %s. Check if the country code is correct.\nExample: /countryinfo/v1/info/NO\nError: %s", return
countryCode, err.Error(),
), http.StatusInternalServerError)
} }
// Returner JSON-respons // Bygg kombinert respons
w.Header().Set("Content-Type", "application/json") response := CombinedInfo{
json.NewEncoder(w).Encode(country) Name: country.Name.Common,
Continents: country.Continents,
Population: country.Population,
Languages: country.Languages,
Borders: country.Borders,
Flags: country.Flags.PNG,
Capital: "",
Cities: "",
} }
// kaller de ulike funkjsonene basert på hvilken URL som sender forespørsel if len(country.Capital) > 0 {
func main() { response.Capital = country.Capital[0]
}
if len(country.Cities) > 0 {
response.Cities = country.Cities[0]
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
func main() {
http.HandleFunc("/", homeHandler) http.HandleFunc("/", homeHandler)
//Rute for info om land http.HandleFunc("/countryinfo/v1/info/", countryInfoHandler)
http.HandleFunc("/countryinfo/v1/info/", handler)
//info i terminal
fmt.Println("Server running on port 8080...") fmt.Println("Server running on port 8080...")
if err := http.ListenAndServe(":8080", nil); err != nil { 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) fmt.Printf("Server failed to start: %s\n", err)
} }
} }
//URL for å teste info for norge func homeHandler(w http.ResponseWriter, r *http.Request) {
//http://localhost:8080/countryinfo/v1/info/No w.Header().Set("Content-Type", "application/json")
\ No newline at end of file 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)
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment