diff --git a/oblig1/endpoints/status.go b/oblig1/endpoints/status.go new file mode 100644 index 0000000000000000000000000000000000000000..bd05cb2a00598c97dacb92c07eb766a6b3b03387 --- /dev/null +++ b/oblig1/endpoints/status.go @@ -0,0 +1,55 @@ +package endpoints + +import ( + "encoding/json" + "net/http" + "time" +) + +// Global variable to store the service start time. +var startTime = time.Now() + +// DiagnosticResponse represents the structure of diagnostics response. +type DiagnosticResponse struct { + GutendexAPIStatus int `json:"gutendexapi"` + LanguageAPIStatus int `json:"languageapi"` + CountriesAPIStatus int `json:"countriesapi"` + Version string `json:"version"` + Uptime float64 `json:"uptime"` +} + +// checkAPIStatus checks the status of an API by sending a GET request and returning the HTTP status code. +func checkAPIStatus(apiURL string) int { + response, err := http.Get(apiURL) + if err != nil { + return http.StatusInternalServerError + } + defer response.Body.Close() + return response.StatusCode +} + +// StatusHandler handles requests to the /librarystats/v1/status/ endpoint. +func StatusHandler(w http.ResponseWriter, r *http.Request) { + // Check the status of Gutendex, Language2Countries, and REST Countries APIs. + gutendexStatus := checkAPIStatus("http://129.241.150.113:8000/") + language2CountriesStatus := checkAPIStatus("http://129.241.150.113:3000/") + restCountriesStatus := checkAPIStatus("http://129.241.150.113:8080/v3.1/alpha/") + + // Example response for testing purposes. + response := DiagnosticResponse{ + GutendexAPIStatus: gutendexStatus, + LanguageAPIStatus: language2CountriesStatus, + CountriesAPIStatus: restCountriesStatus, + Version: "v1", + Uptime: time.Since(startTime).Seconds(), + } + + sendJSONResponse(w, response) +} + +// sendJSONResponse sends a JSON response with the provided data. +func sendJSONResponse(w http.ResponseWriter, data interface{}) { + w.WriteHeader(http.StatusOK) + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(data) +}