Skip to main content

Hooks & Events

Developer Advanced

Use lifecycle hooks and events to extend EZ-Console functionality.

Overviewโ€‹

EZ-Consoleโ€™s authorization stack exposes user change and user role change hooks on server.Service (backed by pkg/service). You need a live Service value to register themโ€”the stock NewCommandServer binary builds that service internally, so wiring hooks from an external app may require a bootstrap that matches your version (for example tests, a fork, or future public extension points). The APIs below are accurate; where you call them depends on how you host the server.

User Change Hooksโ€‹

Registering User Change Hooksโ€‹

Called when user records change (implementation details vary by action). Example shape once you hold svc server.Service:

import (
"context"
"github.com/sven-victor/ez-console/pkg/model"
)

svc.RegisterUserChangeHook(func(ctx context.Context, user *model.User, action string) error {
switch action {
case "create":
sendWelcomeEmail(user)
case "update":
syncUserToExternalSystem(user)
case "delete":
cleanupUserData(user)
}
return nil
})

User Role Change Hooksโ€‹

svc.RegisterUserRoleChangeHook(func(ctx context.Context, userID string, roleIDs []string) error {
updatePermissionsCache(userID, roleIDs)
notifyRoleChange(userID, roleIDs)
return nil
})

Model hooks (GORM)โ€‹

GORM runs lifecycle callbacks on your structs (BeforeCreate, AfterCreate, BeforeUpdate, and so on). Those belong with persistence modeling, not with server.Service hooks above.

See Model lifecycle hooks (GORM) for examples, caveats, and how they interact with model.Base.

Audit loggingโ€‹

Use svc.StartAudit from controllers or services. Audit logging has the complete example and payload shape; Core concepts states when to use it in the overall picture.

Best practicesโ€‹

  • Service hooks (RegisterUserChangeHook, RegisterUserRoleChangeHook): keep them smallโ€”notifications, cache updates, hand-offs to queuesโ€”not large transactions or full business workflows.
  • GORM model callbacks: same idea; put heavy rules in services. See Model lifecycle hooks (GORM).
  • Return errors from hooks when the operation must fail; never swallow failures silently.
  • Respect context.Context for cancellation and deadlines when you do I/O from a hook.

Need help? Ask in GitHub Discussions.