进口结构设置标签我使用gorm(摹ØORM)来检索从我的数据库将在JSON编码数据。 Gorm为主键和时间跟踪提供了一个默认结构,其中的DeletedAt属性不应该用JSON编码。在围棋
我写了一个小例子,即不会输出密码,但DeletedAt属性仍然可见。
package main
import (
"encoding/json"
"fmt"
"os"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
// Struct from the gorm package:
//
// type Model struct {
// ID uint `gorm:"primary_key"`
// CreatedAt time.Time
// UpdatedAt time.Time
// DeletedAt *time.Time
// }
// Defines the database model for gorn
type User struct {
gorm.Model
Username string `json:"username" sql:"size:32; not null; unique"`
Password string `json:"password" sql:"not null"`
Locale string `json:"locale" sql:"not null"`
}
// Public JSON version of database model
type PublicUser struct {
*User
DeletedAt bool `json:"deletedAt,omitempty"`
Password bool `json:"password,omitempty"`
}
func main() {
db, err := gorm.Open("sqlite3", "storage.db")
if err != nil {
fmt.Println(err)
}
u := &User{}
db.Where("id = ?", 3).Find(&u)
json.NewEncoder(os.Stdout).Encode(PublicUser{
User: u,
})
}
这是可能输出我得到的,如果我跑我的脚本:
{
"ID":3,
"CreatedAt":"2015-05-13T14:54:23.5577227Z",
"UpdatedAt":"2015-05-13T14:54:23.5577227Z",
"DeletedAt":null,
"username":"dan",
"locale":"en_US"
}
我修改阿尔弗雷德·罗西的example模仿行为,我得到了相同的结果。
案件事宜。您需要将DeletedAt bool设置为序列化为'json:“DeletedAt,omitempty”。 Captial D在结果中剔除“DeletedAt”。 –