Introduction
BinaryField in Beego ORM is meant for raw binary payloads such as signatures, encrypted blobs, thumbnails, or serialized data. The usual failure mode is subtle: inserts appear to succeed, but reads return empty byte slices, truncated content, or values that no longer match the original payload. In most cases the real issue is not Beego alone, but a mismatch between the Go type, ORM tag, and database column definition.
Symptoms
- The row is inserted, but the binary column comes back empty on read
- Small payloads work, while larger ones are truncated
- The value is stored as text or base64 unexpectedly instead of raw bytes
- The issue appears after migration changes or database driver upgrades
Common Causes
- The model field is not declared as
[]byte - The database column is
VARCHARor another text type instead ofBLOB/BYTEA - ORM migrations created an incompatible column type earlier and the schema drift remained
- The application mutates or reuses the same buffer after insert and before read validation
Step-by-Step Fix
- 1.Verify the model field type and ORM tags
- 2.
BinaryFieldshould be backed by[]byteand should not be mixed with string-oriented tags.
type Document struct {
Id int64
Name string
Payload []byte `orm:"column(payload);type(binary)"`
}- 1.Check the actual database column type
- 2.Confirm the schema matches binary storage in the database you are using.
```sql -- MySQL SHOW CREATE TABLE document;
-- PostgreSQL \d+ document ```
- 1.Insert and read a known byte payload in one tight test
- 2.Use a deterministic payload so you can compare byte-for-byte without application noise.
```go payload := []byte{0x00, 0x01, 0x7f, 0x80, 0xff}
doc := Document{Name: "sample", Payload: payload} _, err := o.Insert(&doc) if err != nil { panic(err) }
loaded := Document{Id: doc.Id} if err := o.Read(&loaded); err != nil { panic(err) }
fmt.Println(bytes.Equal(payload, loaded.Payload)) ```
- 1.Fix schema drift before blaming the ORM
- 2.If the column was created as text earlier, migrate it to a real binary type and retest immediately.
```sql -- MySQL example ALTER TABLE document MODIFY payload LONGBLOB;
-- PostgreSQL example ALTER TABLE document ALTER COLUMN payload TYPE bytea USING decode(encode(payload, 'escape'), 'escape'); ```
Prevention
- Keep
BinaryFieldmodels backed by[]byteonly - Review generated schema after every ORM migration touching binary data
- Add byte-for-byte persistence tests for representative payload sizes
- Avoid mixing application-level encoding assumptions with raw binary storage