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

first attempt of creating API-endpoint for retriving country information based on country code

parent 52d14530
No related branches found
No related tags found
No related merge requests found
Pipeline #30821 failed
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
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment