Files
rpi-sensors/climate-server.go
2020-11-05 00:06:24 +01:00

90 lines
2.1 KiB
Go

package main
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"log"
"net/http"
)
const DEBUG = true
func main() {
err := setup()
defer teardown()
if err == nil {
startServer()
}
}
func setup() error {
err := InitDb()
if err != nil {
return err
}
return nil
}
func teardown() {
CloseDb()
}
func startServer() {
port := "8001"
r := mux.NewRouter()
r.HandleFunc("/", showCharts).Methods("GET")
r.HandleFunc("/data/", sendData).Methods("GET")
r.HandleFunc("/", saveSnapshot).Methods("POST")
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
http.Handle("/", r)
fmt.Printf("Listening on port %s...\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func showCharts(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "charts.html")
}
func sendData(w http.ResponseWriter, r *http.Request) {
records, err := getSnapshotRecordsFromDb(50)
if err != nil {
sendInternalError(fmt.Errorf("couldn't read rows from the database: %w", err), w, r)
return
}
json, err := createJsonFromSnapshotRecords(records)
if err != nil {
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))
if err != nil {
sendInternalError(err, w, r)
return
}
}
func saveSnapshot(w http.ResponseWriter, r *http.Request) {
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
if err != nil {
sendInternalError(fmt.Errorf("couldn't create snapshot from JSON: %w", err), w, r)
}
err = writeSnapshotToDb(snapshotSub)
if err != nil {
sendInternalError(fmt.Errorf("couldn't submit snapshot into the database: %w", err), w, r)
}
}
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)
}