Skip to content
GitLab
Explore
Sign in
Register
Primary navigation
Search or go to…
Project
C
cloud-assignment-02
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
GitLab community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
Nils Petter Skålerud
cloud-assignment-02
Commits
c9e3a410
Commit
c9e3a410
authored
Apr 25, 2023
by
Eimen Ouesalti
Browse files
Options
Downloads
Patches
Plain Diff
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
Changes
1
Show whitespace changes
Inline
Side-by-side
Showing
1 changed file
handlers/historyHandler.go
+94
-18
94 additions, 18 deletions
handlers/historyHandler.go
with
94 additions
and
18 deletions
handlers/historyHandler.go
+
94
−
18
View file @
c9e3a410
...
...
@@ -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
data
set
{
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
}
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment