Skip to content
Snippets Groups Projects
Commit e6570cc7 authored by Marius Nersveen's avatar Marius Nersveen
Browse files

Converting CSV to JSON and then printing it to the web page

parent 932307d5
No related branches found
No related tags found
No related merge requests found
......@@ -12,7 +12,7 @@ func main() {
serverState := utils.ServerState{}
// Extract PORT variable from the environment variables
// Extract PORT variable from the environment variables0
port := os.Getenv("PORT")
// Override port with default port if not provided (e.g. local deployment)
......
......@@ -3,12 +3,42 @@ package handlers
import (
"Assignment02/utils"
"encoding/csv"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
//"strings"
)
func createRenewableEnergyDataset(data [][]string) []utils.StructTest {
// convert csv lines to array of structs
var RenewableEnergyDataset []utils.StructTest
for i, line := range data {
if i > 0 { // omit header line
var rec utils.StructTest
var err error
for j, field := range line {
if j == 0 {
rec.Entity = field
} else if j == 1 {
rec.Code = field
} else if j == 2 {
rec.Year, err = strconv.Atoi(field)
} else if j == 3 {
rec.Renewables, err = strconv.ParseFloat(field, 64)
if err != nil {
continue
}
}
}
RenewableEnergyDataset = append(RenewableEnergyDataset, rec)
}
}
return RenewableEnergyDataset
}
// Dedicated handler for GET requests
func HandleGetRequestForCurrentPercentage(w http.ResponseWriter, r *http.Request) {
......@@ -29,10 +59,24 @@ func HandleGetRequestForCurrentPercentage(w http.ResponseWriter, r *http.Request
// Read the CSV file
fileReader := csv.NewReader(fd)
records, err := fileReader.ReadAll()
data, err := fileReader.ReadAll()
if err != nil {
fmt.Println("Error reading CSV file.")
fmt.Println(err)
}
fmt.Println(records)
//fmt.Println(data) // Print the CSV data to the console
//fmt.Fprintf(w, "%v", data) // Print the CSV data to the browser
// Assign successive lines of raw CSV data to fields of the created structs
RenewableEnergyDataset := createRenewableEnergyDataset(data)
// 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
}
......@@ -48,3 +48,10 @@ type WebhookRegistration struct {
Url string `json:"url"`
Event string `json:"event"`
}
type StructTest struct {
Entity string `json:"Entity"`
Code string `json:"Code"`
Year int `json:"Year"`
Renewables float64 `json:"Renewables (% equivalent primary energy)"`
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment