feat: Add homepage data handlers

This commit is contained in:
ptrcnull 2020-12-23 12:53:56 +01:00
parent f0c009eac5
commit d828c7af24
2 changed files with 29 additions and 20 deletions

37
app.go
View file

@ -9,15 +9,15 @@ import (
"github.com/gofiber/template/html"
)
type App struct {
Config Config
modules map[string]Module
fiber *fiber.App
sessions *session.Store
authHandlers []AuthHandler
viewsFs *utils.JoinedFilesystem
homepage string
Config Config
modules map[string]Module
fiber *fiber.App
sessions *session.Store
authHandlers []AuthHandler
viewsFs *utils.JoinedFilesystem
homepage string
homepageHandlers []func(map[string]interface{})
}
func (app *App) data(ctx *fiber.Ctx, d fiber.Map) fiber.Map {
@ -44,20 +44,27 @@ func New(configs ...Config) *App {
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",
fiber: fiber.New(fiber.Config{Views: views}),
sessions: session.New(),
modules: map[string]Module{},
viewsFs: viewsFs,
homepage: "homepage",
homepageHandlers: []func(map[string]interface{}){},
}
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{
data := app.data(ctx, fiber.Map{
"title": "Homepage",
}), "layouts/main")
})
if app.homepageHandlers != nil && len(app.homepageHandlers) > 0 {
for _, fun := range app.homepageHandlers {
fun(data)
}
}
return ctx.Render(app.homepage, data, "layouts/main")
})
app.fiber.Get("/logout", func(ctx *fiber.Ctx) error {

View file

@ -1,14 +1,15 @@
package modweb
import (
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/session"
"net/http"
)
type ModuleManager struct {
module Module
app *App
app *App
}
func (mm *ModuleManager) RegisterViews(system http.FileSystem) {
@ -29,11 +30,11 @@ func (mm *ModuleManager) Fiber(handlers ...fiber.Handler) fiber.Router {
return ctx.Next()
},
}, handlers...)
return mm.app.fiber.Group("/" + mm.module.Name() + "/", handlers...)
return mm.app.fiber.Group("/"+mm.module.Name()+"/", handlers...)
}
func (mm *ModuleManager) Render(ctx *fiber.Ctx, template string, data fiber.Map) error {
return ctx.Render(mm.module.Name() + "/" + template, mm.app.data(ctx, data), "layouts/main")
return ctx.Render(mm.module.Name()+"/"+template, mm.app.data(ctx, data), "layouts/main")
}
func (mm *ModuleManager) Session(ctx *fiber.Ctx) *session.Session {
@ -51,8 +52,9 @@ func (mm *ModuleManager) User(ctx *fiber.Ctx) *User {
return nil
}
func (mm *ModuleManager) SetHomepage(template string) {
func (mm *ModuleManager) SetHomepage(template string, handlers ...func(map[string]interface{})) {
mm.app.homepage = mm.module.Name() + "/" + template
mm.app.homepageHandlers = handlers
}
func (mm *ModuleManager) SetSessionConfig(config session.Config) {