diff --git a/main.go b/main.go index 85cd6ed4f328b32b9ce98cad9c9a43967b0de604..a6e7110e0430e0200399962aafd0cf5c85cf1a9b 100644 --- a/main.go +++ b/main.go @@ -4,9 +4,59 @@ import ( "encoding/json" "fmt" "net/http" + "time" "strings" ) +var serviceStartTime time.Time + +// Funksjon for å hente statuskode fra et API +func getAPIStatus(url string) (int, error) { + resp, err := http.Get(url) + if err != nil { + return 0, err + } + defer resp.Body.Close() + + // Returner HTTP-statuskoden + return resp.StatusCode, nil +} + +// Funksjon for å beregne oppetid +func getUptime() int64 { + return int64(time.Since(serviceStartTime).Seconds()) +} + +// Handler for Diagnostics endpoint +func diagnosticsHandler(w http.ResponseWriter, r *http.Request) { + // Hent statuskoder fra eksterne API-er + countriesNowStatus, err := getAPIStatus("http://129.241.150.113:3500/api/v0.1/countries") + if err != nil { + http.Error(w, "Error fetching CountriesNow status", http.StatusInternalServerError) + return + } + + restCountriesStatus, err := getAPIStatus("http://129.241.150.113:8080/v3.1/all") //funker med all + if err != nil { + http.Error(w, "Error fetching RestCountries status", http.StatusInternalServerError) + return + } + + // Bygg responsen med statusinformasjon + response := map[string]interface{}{ + "countriesnowapi": fmt.Sprintf("%d", countriesNowStatus), + "restcountriesapi": fmt.Sprintf("%d", restCountriesStatus), + "version": "v1", // Versjon av API + "uptime": getUptime(), // Oppetid i sekunder + } + + // Sett Content-Type til application/json + w.Header().Set("Content-Type", "application/json") + + // Returner JSON-responsen + json.NewEncoder(w).Encode(response) +} + type Flags struct{ PNG string `json:"png"` } @@ -110,6 +160,12 @@ func countryInfoHandler(w http.ResponseWriter, r *http.Request) { } func main() { + +//starttidspunkt for tjenesten + serviceStartTime = time.Now() + + http.HandleFunc("/status/", diagnosticsHandler) + http.HandleFunc("/", homeHandler) http.HandleFunc("/countryinfo/v1/info/", countryInfoHandler) @@ -126,9 +182,13 @@ func homeHandler(w http.ResponseWriter, r *http.Request) { "endpoints": map[string]interface{}{ "Get Country Info": map[string]string{ "Description": "Get country details including cities, population, and more.", - "URL": "http://localhost:8080/countryinfo/v1/info/{country_code}", + "URL Format": "http://localhost:8080/countryinfo/v1/info/{country_code}", "Example": "http://localhost:8080/countryinfo/v1/info/NO", }, + "Get status info" : map[string]string{ + "Description" : "Get information about the API statuses", + "URL" : "http://localhost:8080/status/", + }, }, }