结构看起来像这样:
type Account struct {
Username string // NameKey
Password []byte `datastore:",noindex"`
RegistrationTime time.Time `datastore:",noindex"`
AppUser
}
type AppUser struct {
LoginEntries []LoginEntry `datastore:",noindex"`
}
type LoginEntry struct {
Timestamp time.Time `datastore:",noindex"`
UserAgent string `datastore:",noindex"`
IP string `datastore:",noindex"`
}
我也确定我把数据放对了,因为其他数据更新没有问题,我试过fmt.Println
account Account
的内容对在将它保存在数据存储区之前 (Put(ctx, key, &account
) 并且当我打印它时我可以看到所有的 AppUser
信息..但是当我稍后 获取
用户然后 AppUser
信息不存在(仅显示为 {[]}
)。
我很确定我之前在数据存储中存储了嵌套的结构 slice 没有任何问题,所以我很困惑是什么导致了它..
Put 函数:
func PutAccount(ctx context.Context, acc Account) (*datastore.Key, error) {
if isValidUsername(acc.Username) != true {
return nil, errors.New("Invalid username.")
}
var hashedPassword []byte
if acc.RegistrationTime.IsZero() {
var err error
hashedPassword, err = bcrypt.GenerateFromPassword(acc.Password, 12)
if err != nil {
return nil, err
}
} else {
hashedPassword = acc.Password
}
account := Account{
Username: strings.ToLower(acc.Username),
Password: hashedPassword,
RegistrationTime: time.Now(),
AppUser: acc.AppUser}
fmt.Println("PutAccount, account:", account) // before saving it prints the AppUser without problems
key := datastore.NameKey("Account", account.Username, nil)
return database.DatastoreClient().Put(ctx, key, &account)
}
获取函数:
func GetAccount(ctx context.Context, key *datastore.Key) (Account, error) {
var account Account
err := database.DatastoreClient().Get(ctx, key, &account)
if err != nil {
return account, err
}
return account, nil
}
最佳答案
使用命名结构是可行的。例如:
type Account struct {
Username string // NameKey
Password []byte `datastore:",noindex"`
RegistrationTime time.Time `datastore:",noindex"`
AppUser AppUser
}
至于为什么匿名嵌入式结构不这样做,这可能值得一个 issue .
关于go - 数据存储不会将嵌套结构放入 Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775044/