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

imlemented user firendly feedback with invalid or no given country code

parent 8e625089
No related branches found
No related tags found
No related merge requests found
......@@ -11,7 +11,6 @@ import (
//given country, 2-letter country codes (ISO 3166-2).
//limit is the number of cities that are listed in the response.
// Struktur for å lagre data om landene i info endepunktet
type CountryInfo struct {
Name struct {
......@@ -35,6 +34,7 @@ type CountryInfo struct {
"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" : "To ble implemented",
},
"WELCOME": "Welcome to the Country Info API",
},
......@@ -46,6 +46,7 @@ type CountryInfo struct {
// En funksjon som henter data fra det eksterne API-et ved landkode
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)
......@@ -56,6 +57,7 @@ func getCountryDataByCode(countryCode string) (*CountryInfo, error) {
}
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)
......@@ -82,19 +84,23 @@ func getCountryDataByCode(countryCode string) (*CountryInfo, error) {
// slår opp dataene
// REturnerer dem som JSON
func handler(w http.ResponseWriter, r *http.Request) {
// Hent landkode fra path (for eksempel "/countryinfo/v1/info/NO")
// Hent landkode fra path
parts := strings.Split(r.URL.Path, "/")
if len(parts) < 5 {
http.Error(w, "Invalid format. Please use the format /countryinfo/v1/info/{countryCode}. Example: /countryinfo/v1/info/NO", http.StatusBadRequest)
http.Error(w, "Invalid format. Please use the format /countryinfo/v1/info/{countryCode}{?limit=10}. Example: /countryinfo/v1/info/NO", http.StatusBadRequest)
return
}
countryCode := parts[4] // Landkoden er den 5. delen av pathen (fra 0)
// Hent data fra API ved landkode
//country inneholder data om alt går bra
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", err.Error()), http.StatusInternalServerError)
return
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)
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment