TTime/backend/cmd/main.go

75 lines
1.7 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"
"ttime/internal/config"
2024-02-13 09:20:49 +01:00
"ttime/internal/database"
2024-02-12 12:40:49 +01:00
_ "github.com/mattn/go-sqlite3"
)
2024-02-13 09:19:25 +01:00
// The button state as represented in memory
type ButtonState struct {
2024-02-20 15:26:28 +01:00
PressCount int `json:"pressCount"`
2024-02-13 09:19:25 +01:00
}
// This is what a handler with a receiver looks like
// Keep in mind that concurrent state access is not (usually) safe
2024-02-20 15:55:15 +01:00
// And will in practice be guarded by a mutex
2024-02-13 09:19:25 +01:00
func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) {
2024-02-20 15:54:40 +01:00
if r.Method == "POST" {
2024-02-20 15:26:28 +01:00
b.PressCount++
}
response, err := json.Marshal(b)
2024-02-13 09:19:25 +01:00
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() {
conf, err := config.ReadConfigFromFile("config.toml")
if err != nil {
conf = config.NewConfig()
conf.WriteConfigToFile("config.toml")
}
2024-02-28 08:39:42 +01:00
// Pretty print the current config
str, _ := json.MarshalIndent(conf, "", " ")
fmt.Println(string(str))
2024-02-28 08:39:42 +01:00
database.DbConnect(conf.DbPath)
2024-02-20 15:26:28 +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-20 15:26:28 +01:00
http.HandleFunc("/api/button", b.pressHandler)
2024-02-12 12:40:49 +01:00
2024-02-28 08:39:42 +01:00
// Construct a server URL
server_url := fmt.Sprintf(":%d", conf.Port)
println("Server running on port", conf.Port)
println("Visit http://localhost" + server_url)
2024-02-12 17:23:42 +01:00
println("Press Ctrl+C to stop the server")
2024-02-28 08:39:42 +01:00
err = http.ListenAndServe(server_url, nil)
2024-02-12 12:40:49 +01:00
if err != nil {
panic(err)
}
}