TTime/backend/cmd/main.go

63 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"
"ttime/internal/config"
2024-02-13 09:20:49 +01:00
"ttime/internal/database"
2024-02-12 12:40:49 +01:00
2024-02-28 11:29:32 +01:00
"github.com/gofiber/fiber/v2"
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-28 11:29:32 +01:00
func (b *ButtonState) pressHandlerGet(c *fiber.Ctx) error {
fmt.Println("Get request received")
return c.JSON(b)
2024-02-13 09:19:25 +01:00
}
2024-02-28 11:29:32 +01:00
func (b *ButtonState) pressHandlerPost(c *fiber.Ctx) error {
fmt.Println("Post request received")
b.PressCount++
return c.JSON(b)
2024-02-12 12:40:49 +01:00
}
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-12 12:40:49 +01:00
2024-02-28 11:29:32 +01:00
app := fiber.New()
2024-02-12 12:40:49 +01:00
2024-02-28 11:29:32 +01:00
app.Static("/", "./static")
2024-02-28 08:39:42 +01:00
2024-02-28 11:29:32 +01:00
b := &ButtonState{PressCount: 0}
app.Get("/api/button", b.pressHandlerGet)
app.Post("/api/button", b.pressHandlerPost)
app.Post("/api/project", func(c *fiber.Ctx) error {
return c.JSON(fiber.Map{
"message": "Project created",
})
})
err = app.Listen(fmt.Sprintf(":%d", conf.Port))
2024-02-12 12:40:49 +01:00
if err != nil {
2024-02-28 11:29:32 +01:00
fmt.Println("Error starting server: ", err)
2024-02-12 12:40:49 +01:00
}
}