67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"html/template"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"strconv"
|
|
|
|
"git.dm1sh.ru/dm1sh/gotemptracker/models"
|
|
)
|
|
|
|
func getEnv(name, default_val string) string {
|
|
val := os.Getenv(name)
|
|
|
|
if val == "" {
|
|
return default_val
|
|
}
|
|
|
|
return val
|
|
}
|
|
|
|
var tmpl *template.Template
|
|
|
|
func indexHandler(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method == http.MethodPost {
|
|
strvalue := r.FormValue("value")
|
|
|
|
value, err := strconv.ParseFloat(strvalue, 32)
|
|
if err != nil {
|
|
http.Error(w, "Expected floating point value", http.StatusBadRequest)
|
|
}
|
|
|
|
models.InsertMeasurement(value)
|
|
}
|
|
|
|
measurements, err := models.AllMeasurements()
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
err = tmpl.Execute(w, measurements)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
tmpl = template.Must(template.ParseFiles("index.gohtml"))
|
|
|
|
err := models.InitDB(getEnv("DB_CONNECTION_STRING", "postgres://gotemptracker:gotemptracker@localhost:5432/gotemptracker?sslmode=disable"))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
http.HandleFunc("/", indexHandler)
|
|
|
|
port := getEnv("PORT", "80")
|
|
|
|
log.Printf("Listening on %s\n", port)
|
|
|
|
if err := http.ListenAndServe(":"+port, nil); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|