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

implemented a user friendly home page (from the URL splitted by /, when the...

implemented a user friendly home page (from the URL splitted by /, when the code sends you directly to a webpage without user spesification), explains possible endpoints and how to use them
parent c840ddec
Branches
No related tags found
No related merge requests found
......@@ -7,8 +7,13 @@ import (
"strings"
)
// Struktur for å lagre data om landene
type Country struct {
//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.
// Struktur for å lagre data om landene i info endepunktet
type CountryInfo struct {
Name struct {
Common string `json:"common"`
Official string `json:"official"`
......@@ -18,17 +23,46 @@ type Country struct {
Languages map[string]string `json:"languages"`
}
//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 for info path
func homeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Strukturert respons for bedre lesbarhet
response := map[string]interface{}{
"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",
},
"WELCOME": "Welcome to the Country Info API",
},
}
json.NewEncoder(w).Encode(response)
}
// En funksjon som henter data fra det eksterne API-et ved landkode
func getCountryDataByCode(countryCode string) (*Country, 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)
//sender en http forespørsel
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var countries []Country
// 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
}
......@@ -38,15 +72,20 @@ func getCountryDataByCode(countryCode string) (*Country, error) {
return nil, fmt.Errorf("country not found for code: %s", countryCode)
}
// Returner det første elementet i listen (siden vi forventer bare ett treff)
// 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 (for eksempel "/countryinfo/v1/info/NO")
parts := strings.Split(r.URL.Path, "/")
if len(parts) < 5 {
http.Error(w, "Invalid request 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}. Example: /countryinfo/v1/info/NO", http.StatusBadRequest)
return
}
countryCode := parts[4] // Landkoden er den 5. delen av pathen (fra 0)
......@@ -58,14 +97,29 @@ func handler(w http.ResponseWriter, r *http.Request) {
return
}
// Returner JSON-respons
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(country)
}
// kaller de ulike funkjsonene basert på hvilken URL som sender forespørsel
func main() {
http.HandleFunc("/",homeHandler)
//Rute for info om land
http.HandleFunc("/countryinfo/v1/info/", handler)
//info i terminal
fmt.Println("Server running on port 8080...")
http.ListenAndServe(":8080", 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)
}
}
// http://localhost:8080/countryinfo/v1/info/Norway
\ No newline at end of file
//URL for å teste info for norge
//http://localhost:8080/countryinfo/v1/info/No
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment