我有以下结构定义:
type Job struct {
ID string `json:"id" dynamodbav:"id"`
Ref string `json:"ref_id" dynamodbav:"ref_id"`
Created string `json:"created_at,omitempty" dynamodbav:"created_at"`
Stages map[string]Status `json:"stages,omitempty" dynamodbav:"stages"`
}
// Status interface
type Status interface {
GetMessage() string
}
// Failure struct
type Failure struct {
Message string `json:"error_message,omitempty" dynamodbav:"message"`
}
// GetMessage returns the error message
func (f *Failure) GetMessage() string {
return f.Message
}
// Success struct
type Success struct {
Message string `json:"success_message,omitempty" dynamodbav:"message"`
}
// GetMessage returns the success message
func (s *Success) GetMessage() string {
return s.Message
}
Failure 和 Success 结构满足 Status 接口(interface)的地方我正在尝试将来自 dynamodb 的响应解码到 Job 结构中:
func getJobByID(id, table string) (*Job, error) {
var (
db = dynamodb.New(sess)
key = map[string]*dynamodb.AttributeValue{
"id": {
S: aws.String(id),
},
}
ip = &dynamodb.GetItemInput{
TableName: aws.String(table),
Key: key,
}
)
res, err := db.GetItem(ip)
if err != nil {
return nil, err
}
if res.Item == nil {
return nil, errors.New("Not found")
}
var j *Job
if err := dynamodbattribute.UnmarshalMap(res.Item, &j); err != nil {
return nil, err
}
return j, nil
}
dynamodb 对象看起来像{
"created_at": {
"S": "2020-07-21T06:40:53Z"
},
"id": {
"S": "ca237361-7deb-4a28-872d-a602b9b1df67"
},
"stages": {
"M": {
"stage1": {
"M": {
"message": {
"S": "Completed"
}
}
},
"stage2": {
"M": {
"message": {
"S": "Completed"
}
}
},
"stage3": {
"M": {
"message": {
"S": "Completed"
}
}
}
}
},
"ref_id": {
"S": "test-reference"
}
}
我得到的错误是:panic: reflect.Set: value of type map[string]interface {} is not assignable to type main.Status
我认为问题在于,我正在尝试取消编码类型 string
进入 interface
,并且无法获取导致 panic 的接口(interface)的具体类型。我的问题是如何以惯用的方式解决此问题。
谢谢你们。
最佳答案
不看 dynamodbattribute.UnmarshalMap
的实现, 最后Unmarshal
当您尝试解码到自定义界面时将失败 Status
.这不起作用,因为运行时无法知道要解码的底层结构。
Here's一个类似设置的 Playground 示例,只有 json
.
即使对您的 json 进行目视检查,您也无法确定是否"message": {"S": "Completed"}
是成功还是错误。
您应该替换 Status
在 map[string]Status
使用结构(如下所示)甚至 map[string]string
让编码(marshal)工作
{
Message string
}
基于我之前分享的失败示例,here是让它发挥作用的方法之一。
关于amazon-web-services - 无法将 dynamodb 结果解码为具有定义为类型接口(interface)的字段的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63049268/