85 lines
1.8 KiB
Go
85 lines
1.8 KiB
Go
package modweb
|
|
|
|
import (
|
|
"git.ddd.rip/ptrcnull/modweb/utils"
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/gofiber/session/v2"
|
|
"github.com/gofiber/template/html"
|
|
"github.com/markbates/pkger"
|
|
)
|
|
|
|
|
|
type App struct {
|
|
Config Config
|
|
modules map[string]Module
|
|
fiber *fiber.App
|
|
sessions *session.Session
|
|
authHandlers []AuthHandler
|
|
viewsFs *utils.JoinedFilesystem
|
|
homepage string
|
|
}
|
|
|
|
func (app *App) data(ctx *fiber.Ctx, d fiber.Map) fiber.Map {
|
|
base := fiber.Map{
|
|
"app": app,
|
|
"modules": app.modules,
|
|
"auth": app.authHandlers,
|
|
}
|
|
for k, v := range d {
|
|
base[k] = v
|
|
}
|
|
sess := app.sessions.Get(ctx)
|
|
if _, ok := sess.Get("user:id").(string); ok {
|
|
user := &User{}
|
|
user.Load(sess)
|
|
base["user"] = user
|
|
}
|
|
|
|
return base
|
|
}
|
|
|
|
func New(configs ...Config) *App {
|
|
viewsFs := utils.JoinedFS(pkger.Dir("git.ddd.rip/ptrcnull/modweb:/templates"))
|
|
views := html.NewFileSystem(viewsFs, ".html")
|
|
views.Reload(true)
|
|
app := &App{
|
|
fiber: fiber.New(fiber.Config{Views: views}),
|
|
sessions: session.New(),
|
|
modules: map[string]Module{},
|
|
viewsFs: viewsFs,
|
|
homepage: "homepage",
|
|
}
|
|
if len(configs) > 0 {
|
|
app.Config = configs[0]
|
|
}
|
|
|
|
app.fiber.Get("/", func(ctx *fiber.Ctx) error {
|
|
return ctx.Render(app.homepage, app.data(ctx, fiber.Map{
|
|
"title": "Homepage",
|
|
}), "layouts/main")
|
|
})
|
|
|
|
app.fiber.Get("/logout", func(ctx *fiber.Ctx) error {
|
|
store := app.sessions.Get(ctx)
|
|
store.Destroy()
|
|
return ctx.Redirect("/")
|
|
})
|
|
|
|
return app
|
|
}
|
|
|
|
func (app *App) Register(module Module) {
|
|
app.modules[module.Name()] = module
|
|
module.Init(&ModuleManager{module, app})
|
|
if modAuth, ok := module.(AuthHandler); ok {
|
|
app.authHandlers = append(app.authHandlers, modAuth)
|
|
}
|
|
}
|
|
|
|
func (app *App) Run(addr string) error {
|
|
return app.fiber.Listen(addr)
|
|
}
|
|
|
|
func (app *App) AuthSupported() bool {
|
|
return len(app.authHandlers) > 0
|
|
}
|