I would like to omit some fields in my JSON Response.
Currently I have a type receiver that returns a new struct userToJson
.
I then pass this to the json.NewEncoder()
. However I am wondering if this is the best way to omit fields using GORM.
Thank you beforehand!
package server
import (
"gorm.io/gorm"
)
type User struct {
gorm.Model
FirstName string `gorm:"not null;default:null"`
LastName string `gorm:"not null;default:null"`
Email string `gorm:"not null;default:null;unique"`
Password string `gorm:"not null;default:null"`
Posts []Posts
}
type userToJson struct {
Email string
Posts []Posts
}
func (u *User) toJson() userToJson {
return userToJson{
Email: u.Email,
Posts: u.Posts,
}
}
CodePudding user response:
Another approach is to implement the interface Marshaler
for your type to modify how marshaling to JSON works. The json
package checks for that interface before marshaling, and if it exists, calls that function. Here is the interface from the standard library.
type Marshaler interface {
MarshalJSON() ([]byte, error)
}
One sample implementation for your User
type would be as follows.
func (u *User) MarshalJSON() ([]byte, error) {
type Temp struct {
Email string
Posts []Post
}
t := Temp{
Email: u.Email,
Posts: u.Posts,
}
return json.Marshal(&t)
}