GORM Hooks: BeforeCreate Not Triggered
In this tutorial, you'll learn about GORM Hooks: BeforeCreate Not Triggered. We cover key concepts, practical examples, and best practices.
GORM lifecycle hooks -- Use GORM hooks (BeforeCreate, AfterFind) to run custom logic at specific points in the model lifecycle.
The Problem
GORM hooks are methods on a model struct. BeforeCreate must be named exactly BeforeCreate(tx *gorm.DB) error. Wrong signature = hook silently ignored.
Wrong
type User struct {
ID uint
Password string
}
func (u User) BeforeCreate(tx *gorm.DB) { } // Value receiver, no error!
Output:
// Hook never called. Password stored as plain text.
Right
type User struct { ID uint; Password string }
func (u *User) BeforeCreate(tx *gorm.DB) error {
hashed, _ := bcrypt.GenerateFromPassword([]byte(u.Password), 12)
u.Password = string(hashed)
return nil
}
Output:
// Password hashed before insert
Prevention
- Hooks must use pointer receiver (*User)
- Hooks must return error
- Available: Before/After Save, Create, Update, Delete, Find
- Return error to abort operation
- AfterFind runs after every query
Common Mistakes with gorm 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