Finished?!
This commit is contained in:
145
server.go
Normal file
145
server.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/gorilla/mux"
|
||||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const ROOT_URL = ""
|
||||
|
||||
func startServer() {
|
||||
port := "8001"
|
||||
router := mux.NewRouter()
|
||||
router.HandleFunc("/", showCharts).Methods("GET")
|
||||
router.HandleFunc("/", showCharts).Methods("GET").Queries("show-minutes", "{[0-9]+}")
|
||||
router.HandleFunc("/", saveSnapshot).Methods("POST")
|
||||
router.HandleFunc("/data", sendData).Methods("GET")
|
||||
router.HandleFunc("/data", sendData).Methods("GET").Queries("since", "")
|
||||
router.HandleFunc("/data/now", createAndSendSnapshot).Methods("GET")
|
||||
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("webapp/dist/"))))
|
||||
fmt.Printf("Listening on port %s...\n", port)
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), router))
|
||||
}
|
||||
|
||||
func showCharts(w http.ResponseWriter, r *http.Request) {
|
||||
minutes := r.FormValue("show-minutes")
|
||||
if minutes != "" {
|
||||
if _, err := strconv.ParseInt(minutes, 10, 0); err != nil {
|
||||
http.Redirect(w, r, ROOT_URL, 303)
|
||||
}
|
||||
}
|
||||
templater, err := template.ParseFiles("webapp/dist/charts.html")
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't parse the template: %w", err), w, r) { return }
|
||||
err = templater.Execute(w, ROOT_URL)
|
||||
internalErrorOnErr(err, w, r)
|
||||
}
|
||||
|
||||
func sendData(w http.ResponseWriter, r *http.Request) {
|
||||
dateSince := time.Now()
|
||||
sinceQuery := r.FormValue("since")
|
||||
if sinceQuery != "" {
|
||||
newDateSince, err := time.Parse(time.RFC3339Nano, sinceQuery)
|
||||
if err != nil {
|
||||
http.Redirect(w, r, ROOT_URL, 303)
|
||||
}
|
||||
dateSince = newDateSince
|
||||
}
|
||||
records, err := getSnapshotRecordsFromDb(dateSince)
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't get snapshots from db: %w", err), w, r) { return }
|
||||
json, err := createJsonFromSnapshotRecords(records)
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't create json from snapshots: %w", err), w, r) { return }
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, err = fmt.Fprintf(w, string(json))
|
||||
internalErrorOnErr(err, w, r)
|
||||
}
|
||||
|
||||
func createAndSendSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
snapshot, err := getSnapshotFromPythonScript()
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't create a snapshot: %w", err), w, r) { return }
|
||||
_, err = writeSnapshotToDb(snapshot)
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't save snapshot to db: %w", err), w, r) { return }
|
||||
dbSnapshotRecord, err := getLastSnapshotRecordFromDb()
|
||||
json, err := createJsonFromSnapshotRecords([]*SnapshotRecord{dbSnapshotRecord})
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't create json from last snapshots: %w", err), w, r) { return }
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, err = fmt.Fprintf(w, string(json))
|
||||
internalErrorOnErr(err, w, r)
|
||||
}
|
||||
|
||||
func saveSnapshot(w http.ResponseWriter, r *http.Request) {
|
||||
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't create snapshot from JSON: %w", err), w, r) { return }
|
||||
newId, err := writeSnapshotToDb(snapshotSub)
|
||||
if internalErrorOnErr(fmt.Errorf("couldn't submit snapshot into the database: %w", err), w, r) { return }
|
||||
_, err = fmt.Fprintf(w, "{id: %v}", newId)
|
||||
internalErrorOnErr(err, w, r)
|
||||
}
|
||||
|
||||
func saveSnapshotOnInterval(seconds int64, stop chan int) {
|
||||
for {
|
||||
snapshot, err := getSnapshotFromPythonScript()
|
||||
if err == nil {
|
||||
_, err = writeSnapshotToDb(snapshot)
|
||||
}
|
||||
if err != nil {
|
||||
pythonLogger.Println(err.Error())
|
||||
}
|
||||
select {
|
||||
case <-stop:
|
||||
break
|
||||
default:
|
||||
time.Sleep(time.Duration(seconds) * time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getSnapshotFromPythonScript() (*SnapshotSubmission, error) {
|
||||
output, err := exec.Command("./climate-pinger.py").CombinedOutput()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf(
|
||||
"Error:\n\t%s%w",
|
||||
strings.Replace(string(output), "\n", "\n\t", -1),
|
||||
err,
|
||||
)
|
||||
}
|
||||
tokens := strings.Split(string(output), "\n")
|
||||
if len(tokens) != 4 {
|
||||
return nil, errors.New(fmt.Sprintf("Strange python output: %s", output))
|
||||
}
|
||||
snapshot := SnapshotSubmission{
|
||||
Timestamp: tokens[0],
|
||||
Temp: tokens[1],
|
||||
Humidity: tokens[2],
|
||||
Co2: tokens[3],
|
||||
}
|
||||
return &snapshot, nil
|
||||
}
|
||||
|
||||
func internalErrorOnErr(err error, w http.ResponseWriter, r *http.Request) bool {
|
||||
if errors.Unwrap(err) != nil {
|
||||
errorMessage := "Internal Server Error!"
|
||||
if DEBUG {
|
||||
errorMessage += fmt.Sprintf(" Happened during %s request for pattern '%s': %s",
|
||||
r.Method,
|
||||
r.URL,
|
||||
err.Error())
|
||||
}
|
||||
logError(errorMessage)
|
||||
http.Error(w, errorMessage, 500)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func logError(errorMessage string) {
|
||||
fmt.Println(errorMessage)
|
||||
mainLogger.Println(errorMessage)
|
||||
}
|
||||
Reference in New Issue
Block a user