Skip to content
Snippets Groups Projects
Commit c9e3a410 authored by Eimen Ouesalti's avatar Eimen Ouesalti
Browse files

Created the method handler and the initial version for handling requests without country code

parent 80068c19
No related branches found
No related tags found
No related merge requests found
......@@ -3,16 +3,107 @@ package handlers
import (
"Assignment02/utils"
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"strings"
)
func createRenewableEnergyDatasetTask2(data [][]string) []utils.RenewableEnergy {
// This function is the entry point for historical renewable energy percentage statistics
func HandleGetRequestForHistoricalPercentage(w http.ResponseWriter, r *http.Request) {
//only accept GET method requests
switch r.Method {
case http.MethodGet:
getHandler(w, r)
default:
http.Error(w, "REST Method "+r.Method+" not supported. Currently only "+http.MethodGet+
" is supported.", http.StatusNotImplemented)
return
}
}
func getHandler(w http.ResponseWriter, r *http.Request) {
//Setting the header
w.Header().Set("content-type", "application/json")
// Retrieve the dataset variable
data := parse(utils.RenewableEnergyDataset)
//Retrieve the URL path
parts := strings.Split(r.URL.Path, "/")
//Check the path length and return an error in case there are too many parts
if len(parts) != 6 {
http.Error(w, "Malformed URL. Expected format: ... "+utils.HISTORY_PATH+"<country code>?begin=<year>&end=<year>", http.StatusBadRequest)
return
}
// In case of no country code was provided
if parts[5] == "" {
//check if any time boundaries were specified
if r.URL.RawQuery == "" { //In case no time boundaries were not specified
//Return the information for all years
meanHistoricalPercentage(w, data, 1965, 2021)
}
}
//Return OK status code when finished
http.Error(w, "OK", http.StatusOK)
}
// This function calculates the mean renewable energy percentage in a specific time frame and writes it to the response writer
func meanHistoricalPercentage(w http.ResponseWriter, data []utils.RenewableEnergy, start int, finish int) {
//Instantiate the response variable to be returned to the client
var response []utils.MeanRenewableEnergy
//A variable to keep track of the sum of percentages for each country
var sum float64 = 0
//A variable to keep track of the number of percentages in the sum
num := 0
//Loop over the dataset calculating the mean percentage within the time boundaries for each country
name := data[0].Entity
for _, element := range data {
// Reset the variables and register the results whenever the loop encounters a new country
if element.Entity != name {
if num == 0 {
log.Println(element)
num += 1
}
temp := utils.MeanRenewableEnergy{Entity: name, Code: element.Code, Renewables: sum / float64(num)}
response = append(response, temp)
name = element.Entity
sum = 0
num = 0
}
//Check that the year is within the time limits before updating the variables
if element.Year >= start && element.Year <= finish {
sum += element.Renewables
num += 1
}
}
//Encode and send the response to the client or return an error if the encoding fails
err := json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, "Error occurred while encoding coding the response "+err.Error(), http.StatusInternalServerError)
return
}
}
func parse(dataset [][]string) []utils.RenewableEnergy {
// convert csv lines to array of structs
var RenewableEnergyDataset []utils.RenewableEnergy
for i, line := range data {
for i, line := range dataset {
if i > 0 { // omit header line
var rec utils.RenewableEnergy
var err error
......@@ -35,18 +126,3 @@ func createRenewableEnergyDatasetTask2(data [][]string) []utils.RenewableEnergy
}
return RenewableEnergyDataset
}
func HandleGetRequestForHistoricalPercentage(w http.ResponseWriter, r *http.Request) {
// Assign successive lines of raw CSV data to fields of the created structs
var RenewableEnergyDataset = createRenewableEnergyDatasetTask2(utils.RenewableEnergyDataset)
// Convert an array of structs to JSON using marshaling functions from the encoding/json package
jsonData, err := json.MarshalIndent(RenewableEnergyDataset, "", " ")
if err != nil {
log.Fatal(err)
}
//fmt.Println(string(jsonData)) // Print the JSON data to the console
fmt.Fprintf(w, "%v", string(jsonData)) // Print the JSON data to the browser
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment