GORM provides some default serializers: , gob
, unixtime
, here is a quick example of how to use it.
import "gorm.io/gorm/schema"
type SerializerInterface interface {
Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) error
SerializerValuerInterface
}
type SerializerValuerInterface interface {
Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)
}
For example, the default JSONSerializer
is implemented like:
schema.RegisterSerializer("json", JSONSerializer{})
After registering a serializer, you can use it with the serializer
tag, for example:
Customized Serializer Type
type EncryptedString string
// ctx: contains request-scoped values
// field: the field using the serializer, contains GORM settings, struct tags
// dbValue: current field's value in database
switch value := dbValue.(type) {
case []byte:
*es = EncryptedString(bytes.TrimPrefix(value, []byte("hello")))
case string:
*es = EncryptedString(strings.TrimPrefix(value, "hello"))
default:
return fmt.Errorf("unsupported data %#v", dbValue)
}
return nil
}
// ctx: contains request-scoped values
// field: the field using the serializer, contains GORM settings, struct tags
// dst: current model value, `user` in the below example
// fieldValue: current field's value of the dst
func (es EncryptedString) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error) {
return "hello" + string(es), nil
}
type User struct {
gorm.Model
Password EncryptedString
}
data := User{
Password: EncryptedString("pass"),
}
DB.Create(&data)
// INSERT INTO `serializer_structs` (`password`) VALUES ("hellopass")
var result User
DB.First(&result, "id = ?", data.ID)
// result => User{
// Password: EncryptedString("pass"),
// }
// SELECT * FROM `users` WHERE `users`.`password` = "hellopass"