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 (
"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" {
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++
}
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 handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Request received")
io.WriteString(w, "This is my website!\n")
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)
}
}