Serializing Models
When returning models in API responses, you often need to exclude sensitive fields or pick specific columns. Use database.Serialize, struct tags, or API Resources for more complex transformations.
database.Serialize
Convert a model to a map, controlling which fields are included:
m, err := database.Serialize(user, database.SerializeOptions{
Omit: []string{"password", "remember_token"},
})
return c.JSON(200, m)
// { "id": 1, "name": "Jane", "email": "jane@example.com", "created_at": "..." }
Pick Specific Fields
m, _ := database.Serialize(user, database.SerializeOptions{
Pick: []string{"id", "name", "email"},
})
// { "id": 1, "name": "Jane", "email": "jane@example.com" }
SerializeOptions
| Field | Type | Description |
|---|---|---|
Omit | []string | Fields to exclude from output |
Pick | []string | Only include these fields |
Struct Tags
Permanently hide fields from all JSON output with json:"-":
type User struct {
database.Model
Name string
Email string
Password string `json:"-"` // never serialized
APIKey string `json:"-"` // never serialized
}
// When using c.JSON(200, user), Password and APIKey are excluded
IsDirty
Check if a model has been modified since loading from the database:
// Load from DB
var user User
db.First(&user, 1)
// Modify
user.Name = "Updated"
// Check if changed
if database.IsDirty(&user) {
db.Save(&user)
}
API Example
func ListUsers(c *http.Context) error {
var users []User
database.Get().Find(&users)
// Serialize each user with omitted fields
result := make([]map[string]any, len(users))
for i, u := range users {
result[i], _ = database.Serialize(u, database.SerializeOptions{
Omit: []string{"password", "api_key"},
})
}
return c.JSON(200, result)
}
// For more complex transformations, use API Resources instead