Your Question

Is it possible to create a global hook to prevent duplicated code? Example:

type StructA {
    ID uint `json:"id" gorm:"primaryKey"`
}

func (t *StructA ) AfterCreate(tx *gorm.DB) (err error) {
    // Do something
    return
}

type StructB {
    ID uint `json:"id" gorm:"primaryKey"`
}

func (t *StructB ) AfterCreate(tx *gorm.DB) (err error) {
    // Do the same (or equal) logik like above
    return
}

The document you expected this should be explained

https://gorm.io/docs/hooks.html

Expected answer

I would like to create a global hook that is called for all structs:

func AfterCreate(tx *gorm.DB) (err error) {
        if db.Statement.Schema != nil {
                field := db.Statement.Schema.LookUpField("custom_field")
                if field != nil {
                        // Do something
                }
    return
}

Do I have to use a custom callback for that? Or is there a better solution?

db.Callback().Create().After("gorm:after_create").Register("after_create_custom", AfterCreate)

Comment From: a631807682

Yes, you can register your custom callback.