使用结构更新值

时间:2018-12-04 22:13:42

标签: go amazon-dynamodb

当我在更新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中使用结构?

编辑

根据@Peter的评论,看来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函数中

1 个答案:

答案 0 :(得分:0)

经过几次试验,我终于明白了。我没有测试它,所以我不知道它是否是越野车。但这似乎对我现在有用。

所以我所做的是先用json.Marshal编码结构,然后将json.Unmarshalmap[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
}