Better button handler server-side

This commit is contained in:
Imbus 2024-02-20 15:26:28 +01:00
parent ebe2a42f91
commit 4554ddab6d

View file

@ -12,15 +12,18 @@ import (
// The button state as represented in memory // The button state as represented in memory
type ButtonState struct { type ButtonState struct {
pressCount int PressCount int `json:"pressCount"`
} }
// This is what a handler with a receiver looks like // This is what a handler with a receiver looks like
// Keep in mind that concurrent state access is not (usually) safe // Keep in mind that concurrent state access is not (usually) safe
// And will in pracice be guarded by a mutex // And will in pracice be guarded by a mutex
func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) { func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) {
b.pressCount++ if r.Method != "POST" {
response, err := json.Marshal(b.pressCount) b.PressCount++
}
response, err := json.Marshal(b)
if err != nil { if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
return return
@ -38,13 +41,13 @@ func handler(w http.ResponseWriter, r *http.Request) {
func main() { func main() {
database.DbConnect() database.DbConnect()
b := &ButtonState{pressCount: 0} b := &ButtonState{PressCount: 0}
// Mounting the handlers // Mounting the handlers
fs := http.FileServer(http.Dir("static")) fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs) http.Handle("/", fs)
http.HandleFunc("/hello", handler) http.HandleFunc("/hello", handler)
http.HandleFunc("/button", b.pressHandler) http.HandleFunc("/api/button", b.pressHandler)
// Start the server on port 8080 // Start the server on port 8080
println("Currently listening on http://localhost:8080") println("Currently listening on http://localhost:8080")