Replace fiber with net.http.ServeMux (#23)

This commit is contained in:
T. von Dein
2025-12-23 14:38:45 +01:00
parent 5a705b0af0
commit 3b37a67e02
10 changed files with 306 additions and 183 deletions

View File

@@ -1,5 +1,5 @@
/*
Copyright © 2024 Thomas von Dein
Copyright © 2024-2025 Thomas von Dein
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -17,10 +17,10 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
package rest
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/logger"
"encoding/json"
"log"
"net/http"
"codeberg.org/scip/anydb/cfg"
)
@@ -31,84 +31,62 @@ type Result struct {
Code int `json:"code"`
}
const apiprefix = `/anydb/v1/`
func Runserver(conf *cfg.Config, args []string) error {
// setup api server
router := SetupServer(conf)
mux := http.NewServeMux()
// public rest api routes
api := router.Group("/anydb/v1")
{
api.Get("/", func(c *fiber.Ctx) error {
return RestList(c, conf)
})
api.Post("/", func(c *fiber.Ctx) error {
// same thing as above but allows to supply parameters, see app.Dbattr{}
return RestList(c, conf)
})
api.Get("/:key", func(c *fiber.Ctx) error {
return RestGet(c, conf)
})
api.Delete("/:key", func(c *fiber.Ctx) error {
return RestDelete(c, conf)
})
api.Put("/", func(c *fiber.Ctx) error {
return RestSet(c, conf)
})
}
// public routes
{
router.Get("/", func(c *fiber.Ctx) error {
return c.Send([]byte("Use the REST API"))
})
}
return router.Listen(conf.Listen)
}
func SetupServer(conf *cfg.Config) *fiber.App {
// disable colors
fiber.DefaultColors = fiber.Colors{}
router := fiber.New(fiber.Config{
CaseSensitive: true,
StrictRouting: true,
Immutable: true,
ServerHeader: "anydb serve",
AppName: "anydb",
// just in case someone tries to access the non-api url
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
Home(w)
})
router.Use(logger.New(logger.Config{
Format: "${pid} ${ip}:${port} ${status} - ${method} ${path}\n",
DisableColors: true,
}))
mux.HandleFunc("GET "+apiprefix+"{$}", func(w http.ResponseWriter, r *http.Request) {
RestList(w, r, conf)
})
router.Use(cors.New(cors.Config{
AllowMethods: "GET,PUT,POST,DELETE",
ExposeHeaders: "Content-Type,Accept",
}))
mux.HandleFunc("POST "+apiprefix+"{$}", func(w http.ResponseWriter, r *http.Request) {
RestList(w, r, conf)
})
router.Use(compress.New(compress.Config{
Level: compress.LevelBestSpeed,
}))
mux.HandleFunc("GET "+apiprefix+"{key}", func(w http.ResponseWriter, r *http.Request) {
key := r.PathValue("key")
RestGet(w, r, key, conf)
})
return router
mux.HandleFunc("DELETE "+apiprefix+"{key}", func(w http.ResponseWriter, r *http.Request) {
key := r.PathValue("key")
RestDelete(w, r, key, conf)
})
mux.HandleFunc("PUT "+apiprefix, func(w http.ResponseWriter, r *http.Request) {
RestSet(w, r, conf)
})
logger := LogHandler()
return http.ListenAndServe(conf.Listen, logger(mux))
}
/*
Wrapper to respond with proper json status, message and code,
shall be prepared and called by the handlers directly.
*/
func JsonStatus(c *fiber.Ctx, code int, msg string) error {
success := code == fiber.StatusOK
func JsonStatus(resp http.ResponseWriter, code int, msg string) {
success := code == http.StatusOK
return c.Status(code).JSON(Result{
Code: code,
Message: msg,
Success: success,
})
resp.Header().Set("Content-Type", "application/json")
resp.WriteHeader(code)
err := json.NewEncoder(resp).Encode(
Result{
Code: code,
Message: msg,
Success: success,
})
if err != nil {
log.Fatal(err)
}
}