[英]Why do my struct values not update in the following case when using two goroutines?
[英]Using struct to update values
我在更新dynamodb表的结构中更新空字符串值时陷入困境。
目前我有这个结构
type Client struct {
ClientID *string `json:"client_key,omitempty"`
Name *string `json:"client_name,omitempty"`
Address *string `json:"address,omitempty"`
Country *string `json:"country,omitempty"`
City *string `json:"city,omitempty"`
State *string `json:"state,omitempty"`
PostCode *string `json:"post_code,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
}
而此代码在更新项目时
keyAttr, err := dynamodbattribute.MarshalMap(key)
if err != nil {
return nil, err
}
valAttr, err := dynamodbattribute.MarshalMap(attributes)
if err != nil {
return nil, err
}
keyAttr
将用于Key
字段,而valAttr
将用于ExpressionAttributeValues
字段。 请注意,我没有包括完整的更新字段功能以节省空间。 但是,如果您需要,我会这样做。
目前,该功能运行良好,除非我用空字符串更新了其中一个字段。 例如client.Address = aws.String("")
。 虽然我对dynamodb可以将空字符串转换为null
感到满意,但由于omitempty
标签,我似乎无法找到一种更新方式。
我需要omitempty标签来忽略所有nil
值。 但是,我刚刚研究了omitempty
标签还忽略了空字符串值。 目前,我必须像这样在我的函数中构造一个结构。
type client struct {
Name *string `json:"client_name"`
Address *string `json:"address"`
Country *string `json:"country"`
City *string `json:"city"`
State *string `json:"state"`
PostCode *string `json:"post_code"`
}
但是我不喜欢重复一遍。 因此,问题是:还有更好的方法吗? 你们如何在dynamodb中使用结构?
编辑
根据json.Encode()
的评论,似乎json.Encode()
确实会打印空字符串(如果不是nil的话)。
{"client_key":"test","username":"test","email":"","first_name":"test","last_name":"","phone":"","title":"","email_verified":false,"phone_verified":false,"updated_at":"2018-12-06T14:04:56.2743841+11:00"}
问题似乎在dynamodbattribute.MarshalMap
函数中
经过几次试验,我终于明白了。 我没有测试它,所以我不知道它是否是越野车。 但这似乎对我现在有用。
所以我所做的就是编码与结构json.Marshal
第一,然后使用json.Unmarshal
用map[string]interface{}
然后,我使用dynamodbattribute.Marshal
将其转换为map[string]*AttributeValue
这是代码:
var temp map[string]interface{}
json.Unmarshal(tempStr, &temp)
valAttr, err := dynamodbattribute.MarshalMap(temp)
if err != nil {
return nil, err
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.