Cleaning up examples in main and splitting the code into suitable packages

This commit is contained in:
Imbus 2024-03-02 02:38:26 +01:00
parent 5cefed405f
commit 469f866554
5 changed files with 120 additions and 29 deletions

View file

@ -5,30 +5,12 @@ import (
"fmt"
"ttime/internal/config"
"ttime/internal/database"
"ttime/internal/handlers"
"github.com/gofiber/fiber/v2"
_ "github.com/mattn/go-sqlite3"
)
// The button state as represented in memory
type ButtonState struct {
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 practice be guarded by a mutex
func (b *ButtonState) pressHandlerGet(c *fiber.Ctx) error {
fmt.Println("Get request received")
return c.JSON(b)
}
func (b *ButtonState) pressHandlerPost(c *fiber.Ctx) error {
fmt.Println("Post request received")
b.PressCount++
return c.JSON(b)
}
func main() {
conf, err := config.ReadConfigFromFile("config.toml")
if err != nil {
@ -40,21 +22,21 @@ func main() {
str, _ := json.MarshalIndent(conf, "", " ")
fmt.Println(string(str))
database.DbConnect(conf.DbPath)
// Connect to the database
db := database.DbConnect(conf.DbPath)
// Get our global state
gs := handlers.NewGlobalState(db)
// Create the server
server := fiber.New()
// Mount our static files (Beware of the security implications of this!)
// This will likely be replaced by an embedded filesystem in the future
server.Static("/", "./static")
b := &ButtonState{PressCount: 0}
server.Get("/api/button", b.pressHandlerGet)
server.Post("/api/button", b.pressHandlerPost)
server.Post("/api/project", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"message": "Project created",
})
})
// Register our handlers
server.Post("/api/register", gs.Register)
// Announce the port we are listening on and start the server
err = server.Listen(fmt.Sprintf(":%d", conf.Port))
if err != nil {
fmt.Println("Error starting server: ", err)