Got it working!
This commit is contained in:
73
server.go
73
server.go
@@ -1,73 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"database/sql"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
//"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SnapshotRecord struct {
|
||||
Id int
|
||||
Timestamp time.Time
|
||||
Temp float32
|
||||
Humidity float32
|
||||
Co2 float32
|
||||
}
|
||||
|
||||
type SnapshotSubmission struct {
|
||||
Timestamp float32 `json:"time"`
|
||||
Temp float32 `json:"temp"`
|
||||
Humidity float32 `json:"humidity"`
|
||||
Co2 float32 `json:"co2"`
|
||||
}
|
||||
|
||||
|
||||
var climateDb *sql.DB
|
||||
|
||||
func setupDb() *sql.DB {
|
||||
db, err := sql.Open("mysql", "admin:sekna123jk@tcp(127.0.0.1:3306)/climate")
|
||||
if err != nil {
|
||||
panic(err.Error())
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func main() {
|
||||
climateDb = setupDb()
|
||||
defer climateDb.Close()
|
||||
http.HandleFunc("/", viewHandler)
|
||||
fmt.Println("Listening on port 8001...")
|
||||
log.Fatal(http.ListenAndServe(":8001", nil))
|
||||
}
|
||||
|
||||
func viewHandler(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
_, _ = fmt.Fprint(w, "<h1>Climate Stuff</h1><div>The data will show up here at some stage...</div>")
|
||||
case "POST":
|
||||
var snapshotSub SnapshotSubmission
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error!", 500)
|
||||
}
|
||||
err = json.Unmarshal(body, &snapshotSub)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error!", 500)
|
||||
}
|
||||
_, err = climateDb.Query(
|
||||
fmt.Sprintf("INSERT INTO `snapshots` (`temp`, `humidity`, `co2`, `time`, `id`) VALUES (%v, %v, %v, %v, NULL);",
|
||||
snapshotSub.Temp,
|
||||
snapshotSub.Humidity,
|
||||
snapshotSub.Co2,
|
||||
snapshotSub.Timestamp))
|
||||
if err != nil {
|
||||
http.Error(w, "Internal Server Error!", 500)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user