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