Porting to fiber

This commit is contained in:
Imbus 2024-02-28 11:29:32 +01:00
parent 4c7a3fd9a0
commit d51b9f78c2

View file

@ -3,11 +3,10 @@ package main
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io"
"net/http"
"ttime/internal/config" "ttime/internal/config"
"ttime/internal/database" "ttime/internal/database"
"github.com/gofiber/fiber/v2"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
@ -19,25 +18,15 @@ type ButtonState struct {
// This is what a handler with a receiver looks like // This is what a handler with a receiver looks like
// Keep in mind that concurrent state access is not (usually) safe // Keep in mind that concurrent state access is not (usually) safe
// And will in practice be guarded by a mutex // And will in practice be guarded by a mutex
func (b *ButtonState) pressHandler(w http.ResponseWriter, r *http.Request) { func (b *ButtonState) pressHandlerGet(c *fiber.Ctx) error {
if r.Method == "POST" { fmt.Println("Get request received")
b.PressCount++ return c.JSON(b)
}
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))
} }
// This is what a handler looks like func (b *ButtonState) pressHandlerPost(c *fiber.Ctx) error {
func handler(w http.ResponseWriter, r *http.Request) { fmt.Println("Post request received")
fmt.Println("Request received") b.PressCount++
io.WriteString(w, "This is my website!\n") return c.JSON(b)
} }
func main() { func main() {
@ -52,23 +41,22 @@ func main() {
fmt.Println(string(str)) fmt.Println(string(str))
database.DbConnect(conf.DbPath) database.DbConnect(conf.DbPath)
app := fiber.New()
app.Static("/", "./static")
b := &ButtonState{PressCount: 0} 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 err = app.Listen(fmt.Sprintf(":%d", conf.Port))
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)
if err != nil { if err != nil {
panic(err) fmt.Println("Error starting server: ", err)
} }
} }