From d51b9f78c2e20234b6c8482c3719fb6b1e21c129 Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Wed, 28 Feb 2024 11:29:32 +0100 Subject: [PATCH] Porting to fiber --- backend/cmd/main.go | 56 ++++++++++++++++++--------------------------- 1 file changed, 22 insertions(+), 34 deletions(-) diff --git a/backend/cmd/main.go b/backend/cmd/main.go index ea8d968..ee394ca 100644 --- a/backend/cmd/main.go +++ b/backend/cmd/main.go @@ -3,11 +3,10 @@ package main import ( "encoding/json" "fmt" - "io" - "net/http" "ttime/internal/config" "ttime/internal/database" + "github.com/gofiber/fiber/v2" _ "github.com/mattn/go-sqlite3" ) @@ -19,25 +18,15 @@ type ButtonState struct { // 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) pressHandler(w http.ResponseWriter, r *http.Request) { - if r.Method == "POST" { - b.PressCount++ - } - - response, err := json.Marshal(b) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - - fmt.Println("Request received") - io.WriteString(w, string(response)) +func (b *ButtonState) pressHandlerGet(c *fiber.Ctx) error { + fmt.Println("Get request received") + return c.JSON(b) } -// 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 (b *ButtonState) pressHandlerPost(c *fiber.Ctx) error { + fmt.Println("Post request received") + b.PressCount++ + return c.JSON(b) } func main() { @@ -52,23 +41,22 @@ func main() { fmt.Println(string(str)) database.DbConnect(conf.DbPath) + + app := fiber.New() + + app.Static("/", "./static") + 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", + }) + }) - // Mounting the handlers - fs := http.FileServer(http.Dir("static")) - http.Handle("/", fs) - http.HandleFunc("/hello", handler) - http.HandleFunc("/api/button", b.pressHandler) - - // Construct a server URL - server_url := fmt.Sprintf(":%d", conf.Port) - - println("Server running on port", conf.Port) - println("Visit http://localhost" + server_url) - println("Press Ctrl+C to stop the server") - - err = http.ListenAndServe(server_url, nil) + err = app.Listen(fmt.Sprintf(":%d", conf.Port)) if err != nil { - panic(err) + fmt.Println("Error starting server: ", err) } }