added visualisation

This commit is contained in:
Daniel Ledda
2020-11-04 23:50:44 +01:00
parent 42dfd20eb9
commit 4c106fd763
5 changed files with 20933 additions and 27 deletions

View File

@@ -3,6 +3,7 @@ package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"log"
"net/http"
)
@@ -31,40 +32,57 @@ func teardown() {
func startServer() {
port := "8001"
MainRouter.setGet("/", showCharts)
MainRouter.setGet("/data/", sendData)
MainRouter.setPost("/", saveSnapshot)
r := mux.NewRouter()
r.HandleFunc("/", showCharts).Methods("GET")
r.HandleFunc("/data", sendData).Methods("GET")
r.HandleFunc("/", saveSnapshot).Methods("POST")
http.Handle("/", r)
fmt.Printf("Listening on port %s...\n", port)
log.Fatal(http.ListenAndServe(":" + port, nil))
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func showCharts(w http.ResponseWriter, r *http.Request) error {
_, err := fmt.Fprint(w, "<h1>Climate Stuff</h1><div>The data will show up here at some stage...</div>")
return err
func showCharts(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "charts.html")
}
func sendData(w http.ResponseWriter, r *http.Request) error {
func sendData(w http.ResponseWriter, r *http.Request) {
records, err := getSnapshotRecordsFromDb(50)
if err != nil {
return fmt.Errorf("couldn't read rows from the database: %w", err)
sendInternalError(fmt.Errorf("couldn't read rows from the database: %w", err), w, r)
return
}
json, err := createJsonFromSnapshotRecords(records)
if err != nil {
return fmt.Errorf("couldn't create a json from the records: %w", err)
sendInternalError(fmt.Errorf("couldn't create a json from the records: %w", err), w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = fmt.Fprintf(w, string(json))
return err
if err != nil {
sendInternalError(err, w, r)
return
}
}
func saveSnapshot(w http.ResponseWriter, r *http.Request) error {
func saveSnapshot(w http.ResponseWriter, r *http.Request) {
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
if err != nil {
return fmt.Errorf("couldn't create snapshot from JSON: %w", err)
sendInternalError(fmt.Errorf("couldn't create snapshot from JSON: %w", err), w, r)
}
err = writeSnapshotToDb(snapshotSub)
if err != nil {
return fmt.Errorf("couldn't submit snapshot into the database: %w", err)
sendInternalError(fmt.Errorf("couldn't submit snapshot into the database: %w", err), w, r)
}
return nil
}
}
func sendInternalError(err error, w http.ResponseWriter, r *http.Request) {
errorMessage := "Internal Server Error!"
if DEBUG {
errorMessage += fmt.Sprintf(" Happened during %s request for pattern '%s': %s",
r.Method,
r.URL,
err.Error())
}
fmt.Println(errorMessage)
http.Error(w, errorMessage, 500)
}