Go Ent Hooks
In this tutorial, you'll learn about Ent Hooks: Mutation Interception. We cover key concepts, practical examples, and best practices.
Ent hooks and interceptors -- Run custom logic on Ent mutations using hooks that wrap create, update, delete operations.
The Problem
Ent hooks require correct signature and must be registered on the client. The hook receives a next function to continue the chain.
Wrong
client.User.Create().SetName("Alice").Save(ctx)
Output:
// No hooks configured. Password stored in plain text.
Right
func hashPasswordHook() ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if userMut, ok := m.(*gen.UserMutation); ok {
if pwd, exists := userMut.Password(); exists {
hashed, _ := bcrypt.GenerateFromPassword([]byte(pwd), 12)
userMut.SetPassword(string(hashed))
}
}
return next.Mutate(ctx, m)
})
}
}
client.User.Use(hashPasswordHook())
Output:
// Password hashed before every Create/Update
Prevention
- Hooks wrap mutation with next.Mutate()
- Type assert to access specific mutation
- Run for Create, Update, Delete
- Register with client.User.Use()
- Return error to abort
Common Mistakes with ent hooks
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro