humiditycalc/server/server.go

49 lines
1.1 KiB
Go
Raw Normal View History

2024-10-26 14:31:51 +00:00
package server
import (
2024-10-26 17:53:38 +00:00
"html/template"
2024-10-26 14:31:51 +00:00
"net/http"
"strconv"
"github.com/LeRoid-hub/humiditycalc/internal"
)
2024-10-26 17:53:38 +00:00
type result struct {
AbsoluteHumidity float64
}
2024-10-26 14:31:51 +00:00
// StartServer starts the HTTP server.
func Run() {
2024-10-26 17:53:38 +00:00
tmpl := template.Must(template.ParseFiles("./web/templates/index.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Parse query parameters
tempCelsius, relativeHumidity := r.URL.Query().Get("temp"), r.URL.Query().Get("rh")
if tempCelsius == "" || relativeHumidity == "" {
tmpl.Execute(w, nil)
return
}
// Convert query parameters to float64
temp, err := strconv.ParseFloat(tempCelsius, 32)
if err != nil {
http.Error(w, "invalid temperature value", http.StatusBadRequest)
return
}
rh, err := strconv.ParseFloat(relativeHumidity, 32)
if err != nil {
http.Error(w, "invalid relative humidity value", http.StatusBadRequest)
return
}
// Calculate absolute humidity
absoluteHumidity := internal.AbsoluteHumidity(temp, rh)
// Write response
tmpl.Execute(w, result{AbsoluteHumidity: absoluteHumidity})
})
2024-10-26 14:31:51 +00:00
http.ListenAndServe(":8080", nil)
}