Files
anydb/rest/serve.go

114 lines
2.7 KiB
Go
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
Copyright © 2024 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
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package rest
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/compress"
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/gofiber/fiber/v3/middleware/logger"
"github.com/gofiber/fiber/v3/middleware/requestid"
"github.com/tlinden/anydb/cfg"
)
// used to return to the api client
type Result struct {
Success bool `json:"success"`
Message string `json:"message"`
Code int `json:"code"`
}
func Runserver(conf *cfg.Config, args []string) error {
// setup api server
router := SetupServer(conf)
// public rest api routes
api := router.Group("/anydb/v1")
{
api.Get("/", func(c fiber.Ctx) error {
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("/", nil, 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 {
router := fiber.New(fiber.Config{
CaseSensitive: true,
StrictRouting: true,
Immutable: true,
ServerHeader: "anydb serve",
AppName: "anydb",
})
router.Use(requestid.New())
router.Use(logger.New(logger.Config{
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
}))
router.Use(cors.New(cors.Config{
AllowMethods: []string{"GET", "PUT", "POST", "DELETE"},
ExposeHeaders: []string{"Content-Type", "Accept"},
}))
router.Use(compress.New(compress.Config{
Level: compress.LevelBestSpeed,
}))
return router
}
/*
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 := true
if code != fiber.StatusOK {
success = false
}
return c.Status(code).JSON(Result{
Code: code,
Message: msg,
Success: success,
})
}