From c840ddec9dfe368b44aebc3ddba9aefd81d1ef7a Mon Sep 17 00:00:00 2001 From: Mathilde Hertaas <maimh@stud.ntnu.no> Date: Tue, 25 Feb 2025 14:19:34 +0100 Subject: [PATCH] first attempt of creating API-endpoint for retriving country information based on country code --- main.go | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index 6eb74fc..68626d8 100644 --- a/main.go +++ b/main.go @@ -1,16 +1,71 @@ package main import ( + "encoding/json" "fmt" "net/http" + "strings" ) +// Struktur for å lagre data om landene +type Country struct { + Name struct { + Common string `json:"common"` + Official string `json:"official"` + } `json:"name"` + Capital []string `json:"capital"` + Region string `json:"region"` + Languages map[string]string `json:"languages"` +} + +// En funksjon som henter data fra det eksterne API-et ved landkode +func getCountryDataByCode(countryCode string) (*Country, error) { + url := fmt.Sprintf("http://129.241.150.113:8080/v3.1/alpha/%s", countryCode) + + resp, err := http.Get(url) + if err != nil { + return nil, err + } + defer resp.Body.Close() + + var countries []Country + 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 vi forventer bare ett treff) + return &countries[0], nil +} + func handler(w http.ResponseWriter, r *http.Request) { - fmt.Fprintf(w, "Hello, Cloud Technologies!") + // 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) + return + } + countryCode := parts[4] // Landkoden er den 5. delen av pathen (fra 0) + + // Hent data fra API ved landkode + country, err := getCountryDataByCode(countryCode) + 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 + } + + // Returner JSON-respons + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(country) } func main() { - http.HandleFunc("/", handler) + http.HandleFunc("/countryinfo/v1/info/", handler) fmt.Println("Server running on port 8080...") http.ListenAndServe(":8080", nil) -} \ No newline at end of file +} +// http://localhost:8080/countryinfo/v1/info/Norway \ No newline at end of file -- GitLab