You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
website/services/server/router/router.go

74 lines
1.5 KiB
Go

package router
import (
"bytes"
"log"
"os"
"git.phc.dm.unipi.it/phc/website/services/server/dev"
"git.phc.dm.unipi.it/phc/website/services/server/routes"
"git.phc.dm.unipi.it/phc/website/sl"
"github.com/gofiber/fiber/v2"
)
// assert type of [ServerRequest] is [dev.Request]
var _ dev.Request = ServerRequest{}
// ServerRequest is used when the request is directly for the Go server
type ServerRequest struct {
page []byte
fiberContext *fiber.Ctx
}
func (r ServerRequest) Page() []byte {
return r.page
}
func (ctx ServerRequest) Param(key string) string {
return ctx.fiberContext.Params(key)
}
func (ctx ServerRequest) Query(key string) string {
return ctx.fiberContext.Query(key)
}
func UseRoutePage(l *sl.ServiceLocator, route, frontendFile string) {
root, err := sl.Use(l, routes.Root)
if err != nil {
log.Fatal(err)
}
dev.RegisterRoute(l, route, frontendFile)
root.Get(route, func(c *fiber.Ctx) error {
return c.SendFile(dev.GetArtifactPath(frontendFile))
})
}
func UseRouteTemplatedPage(l *sl.ServiceLocator, route, frontendFile string, handler dev.Handler) {
r, err := sl.Use(l, routes.Root)
if err != nil {
log.Fatal(err)
}
dev.RegisterDynamicRoute(l, route, frontendFile, handler)
r.Get(route, func(c *fiber.Ctx) error {
rawPage, err := os.ReadFile(dev.GetArtifactPath(frontendFile))
if err != nil {
return err
}
var buf bytes.Buffer
if err := handler(&buf, ServerRequest{
rawPage,
c,
}); err != nil {
return err
}
return c.Type(".html").Send(buf.Bytes())
})
}