diff --git a/handelers/constants.go b/handelers/constants.go index dcd066ea32bb48f5ba04e9c447679aa8f1b75b59..85cf81170caacb5e3f14dd80c3a11e1e685f4518 100644 --- a/handelers/constants.go +++ b/handelers/constants.go @@ -2,12 +2,14 @@ package handelers //URL const HOMEPAGE_DEFAULT = "http://localhost:8080" -const INFO_DEFAULT = "/countryinfo/vi/info/" +const INFO_DEFAULT = "/countryinfo/v1/info/" const POPULATION_DEFAULT = "/population/" const STATUS_DEFAULT = "/status/" const SLASH_DEFAULT = "/" //ERRORS +const CITIES_ERROR = "error retrieving cities, status code: " +const CITIES_ERROR2 = "no cities found for country %s" //Terminal info const RUNNING_ON_PORT = "" @@ -39,6 +41,17 @@ const INTRO = "API status" const FORMAT_JSON = "application/json" const HEADER_CONTENT_TYPE = "Content-Type" +//info +const URL_API = "http://129.241.150.113:8080/v3.1/alpha/" +const ERROR_RETRIEVING_COUNTRY_DATA = "error retrieving country data for country code: %s\n" +const COUNTRY_CODE_REMINDER = "Remember to use the 2-letter country code (ISO 3166-2).\n" +const CITY_LIMIT_REMINDER = "You can also specify how many cities to display with {?limit=<some_value>}.\n" +const EXAMPLE_URL = "Example: %s\n" +const ASSISTANCE_REMINDER = "If you need further assistance, please visit the homepage at: %s" +const CITIES = "cities" +const CITIES_URL = "https://countriesnow.space/api/v0.1/countries/cities/q?country=" +const DATA = "data" + //extern API const COUNTRIESNOW_API = "http://129.241.150.113:3500/api/v0.1/countries" const RESTCOUNTRIES_API = "http://129.241.150.113:8080/v3.1/all" \ No newline at end of file diff --git a/handelers/infohandler.go b/handelers/infohandler.go index 021905f67653c1b1f0a2c2712950fd2327c2b0f3..7bf229d1ed4385e0c08af0221b053e2b130f5456 100644 --- a/handelers/infohandler.go +++ b/handelers/infohandler.go @@ -8,9 +8,8 @@ import( "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) + url := fmt.Sprintf(URL_API + "%s", countryCode) resp, err := http.Get(url) if err != nil { return nil, err @@ -18,64 +17,49 @@ func getCountryDataByCode(countryCode string) (*CountryInfo, error) { defer resp.Body.Close() 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 + + COUNTRY_CODE_REMINDER + + CITY_LIMIT_REMINDER + + EXAMPLE_URL + + ASSISTANCE_REMINDER, + countryCode, INFO_URL_EXAMPLE, HOMEPAGE_DEFAULT) } - 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 - } + parts := strings.Split(r.URL.Path, SLASH_DEFAULT) 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 + cityCount := 10 // Default + cityCountStr := r.URL.Query().Get(CITIES) if cityCountStr != "" { - // Prøv å konvertere parameteren til et heltall if count, err := strconv.Atoi(cityCountStr); err == nil && count > 0 { - cityCount = count + cityCount = count //number of cities to be displayed if specified } } - // 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, @@ -84,20 +68,19 @@ func CountryInfoHandler(w http.ResponseWriter, r *http.Request) { Borders: country.Borders, Flags: country.Flags.PNG, Capital: "", - Cities: strings.Join(cities, ", "), // Legg til de 10 første byene som en kommaseparert liste + Cities: strings.Join(cities, ", "), } if len(country.Capital) > 0 { response.Capital = country.Capital[0] } - // Sett Content-Type til application/json - w.Header().Set("Content-Type", "application/json") + w.Header().Set(HEADER_CONTENT_TYPE, FORMAT_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) + url := fmt.Sprintf(CITIES_URL +"%s", countryName) resp, err := http.Get(url) if err != nil { return nil, err @@ -105,7 +88,7 @@ func getCitiesByCountry(countryName string) ([]string, error) { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("error retrieving cities, status code: %d", resp.StatusCode) + return nil, fmt.Errorf(CITIES_ERROR + "%d", resp.StatusCode) } var responseBody map[string]interface{} @@ -113,22 +96,15 @@ func getCitiesByCountry(countryName string) ([]string, error) { return nil, err } - - if cities, ok := responseBody["data"].([]interface{}); ok { + 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) + return nil, fmt.Errorf(CITIES_ERROR2, countryName) } \ No newline at end of file