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-11-02 12:24:36 +00:00
|
|
|
// Run starts the HTTP server.
|
2024-10-26 14:31:51 +00:00
|
|
|
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)
|
|
|
|
|
|
|
|
}
|