撰寫外掛

Callbacks

GORM 利用 Callbacks 來強化其核心功能。這些 callback 提供各種資料庫操作的掛鉤,例如 CreateQueryUpdateDeleteRowRaw,允許廣泛自訂 GORM 的行為。

Callbacks 在全域 *gorm.DB 層級註冊,而非在會話基礎上。這表示如果您需要不同的 callback 行為,您應該初始化一個獨立的 *gorm.DB 實例。

註冊 Callback

您可以為特定操作註冊 callback。例如,要新增自訂影像裁切功能

func cropImage(db *gorm.DB) {
if db.Statement.Schema != nil {
// crop image fields and upload them to CDN, dummy code
for _, field := range db.Statement.Schema.Fields {
switch db.Statement.ReflectValue.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < db.Statement.ReflectValue.Len(); i++ {
// Get value from field
if fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue.Index(i)); !isZero {
if crop, ok := fieldValue.(CropInterface); ok {
crop.Crop()
}
}
}
case reflect.Struct:
// Get value from field
if fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue); !isZero {
if crop, ok := fieldValue.(CropInterface); ok {
crop.Crop()
}
}

// Set value to field
err := field.Set(db.Statement.Context, db.Statement.ReflectValue, "newValue")
}
}

// All fields for current model
db.Statement.Schema.Fields

// All primary key fields for current model
db.Statement.Schema.PrimaryFields

// Prioritized primary key field: field with DB name `id` or the first defined primary key
db.Statement.Schema.PrioritizedPrimaryField

// All relationships for current model
db.Statement.Schema.Relationships

// Find field with field name or db name
field := db.Statement.Schema.LookUpField("Name")

// processing
}
}

// Register the callback for the Create operation
db.Callback().Create().Register("crop_image", cropImage)

刪除 Callback

如果不再需要 callback,可以將其移除

// Remove the 'gorm:create' callback from Create operations
db.Callback().Create().Remove("gorm:create")

取代 Callback

具有相同名稱的 callback 可以用新的函式取代

// Replace the 'gorm:create' callback with a new function
db.Callback().Create().Replace("gorm:create", newCreateFunction)

排序 Callbacks

Callbacks 可以註冊為特定順序,以確保它們在操作生命週期中正確的時間執行。

// Register to execute before the 'gorm:create' callback
db.Callback().Create().Before("gorm:create").Register("update_created_at", updateCreated)

// Register to execute after the 'gorm:create' callback
db.Callback().Create().After("gorm:create").Register("update_created_at", updateCreated)

// Register to execute after the 'gorm:query' callback
db.Callback().Query().After("gorm:query").Register("my_plugin:after_query", afterQuery)

// Register to execute after the 'gorm:delete' callback
db.Callback().Delete().After("gorm:delete").Register("my_plugin:after_delete", afterDelete)

// Register to execute before the 'gorm:update' callback
db.Callback().Update().Before("gorm:update").Register("my_plugin:before_update", beforeUpdate)

// Register to execute before 'gorm:create' and after 'gorm:before_create'
db.Callback().Create().Before("gorm:create").After("gorm:before_create").Register("my_plugin:before_create", beforeCreate)

// Register to execute before any other callbacks
db.Callback().Create().Before("*").Register("update_created_at", updateCreated)

// Register to execute after any other callbacks
db.Callback().Create().After("*").Register("update_created_at", updateCreated)

預定義 Callbacks

GORM 附帶一組預定義 callback,用於驅動其標準功能。建議在建立自訂外掛或額外 callback 函式之前,先檢閱這些 已定義的 callback

外掛

GORM 的外掛系統允許輕鬆擴充和自訂其核心功能,在維持模組化架構的同時,強化應用程式的功能。

Plugin 介面

要為 GORM 建立外掛,您需要定義一個實作 Plugin 介面的結構

type Plugin interface {
Name() string
Initialize(*gorm.DB) error
}
  • Name 方法:傳回外掛的唯一字串識別碼。
  • Initialize 方法:包含設定外掛的邏輯。此方法會在外掛第一次向 GORM 註冊時呼叫。

註冊外掛程式

外掛程式符合Plugin介面後,可以將其註冊至 GORM 實例

// Example of registering a plugin
db.Use(MyCustomPlugin{})

存取已註冊外掛程式

外掛程式註冊後,會儲存在 GORM 的組態中。你可以透過Plugins地圖存取已註冊的外掛程式

// Access a registered plugin by its name
plugin := db.Config.Plugins[pluginName]

實務範例

GORM 外掛程式的範例是 Prometheus 外掛程式,它將 Prometheus 監控整合至 GORM

// Registering the Prometheus plugin
db.Use(prometheus.New(prometheus.Config{
// Configuration options here
}))

Prometheus 外掛程式文件提供了其實作和用法的詳細資訊。

白金贊助商

金牌贊助商

白金贊助商

金牌贊助商