GORM provides some default serializers: , gob, unixtime, here is a quick example of how to use it.

    1. import "gorm.io/gorm/schema"
    2. type SerializerInterface interface {
    3. Scan(ctx context.Context, field *schema.Field, dst reflect.Value, dbValue interface{}) error
    4. SerializerValuerInterface
    5. }
    6. type SerializerValuerInterface interface {
    7. Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error)
    8. }

    For example, the default JSONSerializer is implemented like:

    1. schema.RegisterSerializer("json", JSONSerializer{})

    After registering a serializer, you can use it with the serializer tag, for example:

    Customized Serializer Type

    1. type EncryptedString string
    2. // ctx: contains request-scoped values
    3. // field: the field using the serializer, contains GORM settings, struct tags
    4. // dbValue: current field's value in database
    5. switch value := dbValue.(type) {
    6. case []byte:
    7. *es = EncryptedString(bytes.TrimPrefix(value, []byte("hello")))
    8. case string:
    9. *es = EncryptedString(strings.TrimPrefix(value, "hello"))
    10. default:
    11. return fmt.Errorf("unsupported data %#v", dbValue)
    12. }
    13. return nil
    14. }
    15. // ctx: contains request-scoped values
    16. // field: the field using the serializer, contains GORM settings, struct tags
    17. // dst: current model value, `user` in the below example
    18. // fieldValue: current field's value of the dst
    19. func (es EncryptedString) Value(ctx context.Context, field *schema.Field, dst reflect.Value, fieldValue interface{}) (interface{}, error) {
    20. return "hello" + string(es), nil
    21. }
    22. type User struct {
    23. gorm.Model
    24. Password EncryptedString
    25. }
    26. data := User{
    27. Password: EncryptedString("pass"),
    28. }
    29. DB.Create(&data)
    30. // INSERT INTO `serializer_structs` (`password`) VALUES ("hellopass")
    31. var result User
    32. DB.First(&result, "id = ?", data.ID)
    33. // result => User{
    34. // Password: EncryptedString("pass"),
    35. // }
    36. // SELECT * FROM `users` WHERE `users`.`password` = "hellopass"