[英]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.