TTime/backend/cmd/main.go

59 lines
1.4 KiB
Go
Raw Normal View History

2024-02-12 12:40:49 +01:00
package main
import (
2024-02-13 09:19:25 +01:00
"encoding/json"
2024-02-12 12:40:49 +01:00
"fmt"
"io"
"net/http"
"tmp/internal/database"
_ "github.com/mattn/go-sqlite3"
)
2024-02-13 09:19:25 +01:00
// The button state as represented in memory
type ButtonState struct {
pressCount int
}
// 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 err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Println("Request received")
io.WriteString(w, string(response))
}
2024-02-12 12:40:49 +01:00
// This is what a handler looks like
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Request received")
io.WriteString(w, "This is my website!\n")
}
func main() {
database.DbConnect()
2024-02-13 09:19:25 +01:00
b := &ButtonState{pressCount: 0}
2024-02-12 12:40:49 +01:00
2024-02-13 09:19:25 +01:00
// Mounting the handlers
2024-02-12 12:40:49 +01:00
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
http.HandleFunc("/hello", handler)
2024-02-13 09:19:25 +01:00
http.HandleFunc("/button", b.pressHandler)
2024-02-12 12:40:49 +01:00
// Start the server on port 8080
2024-02-12 17:20:42 +01:00
println("Currently listening on http://localhost:8080")
2024-02-13 09:19:25 +01:00
println("Visit http://localhost:8080/hello to see the hello handler in action")
println("Visit http://localhost:8080/button to see the button handler in action")
2024-02-12 17:23:42 +01:00
println("Press Ctrl+C to stop the server")
2024-02-12 12:40:49 +01:00
err := http.ListenAndServe(":8080", nil)
if err != nil {
panic(err)
}
}