Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

service/dynamodb/dynamodbattribute: UnmarshalTypeError: cannot unmarshal string into Go value of type kind.UserStatus #1917

Closed
zero-master opened this issue Apr 27, 2018 · 1 comment

Comments

@zero-master
Copy link

zero-master commented Apr 27, 2018

Version of AWS SDK for Go?

Updated using go get -u github.com/aws/aws-sdk-go/... today

Version of Go (go version)?

go version go1.10.1 linux/amd64

What issue did you see?

`2018/04/27 18:28:36 UnmarshalTypeError: cannot unmarshal string into Go value of type kind.UserStatus

Steps to reproduce

I am using:
https://github.com/campoy/jsonenums
https://godoc.org/golang.org/x/tools/cmd/stringer

package kind


//go:generate stringer -type=UserStatus
//go:generate jsonenums -type=UserStatus
type UserStatus int

const (
	IN_ACTIVE UserStatus = iota
	EMAIL_UNVERIFIED
	ACTIVE
	CLOSED
	DELETED
)

type User struct {
	ID                 string             `json:"id"`
	Status             kind.UserStatus    `json:"status"`
}
user := model.User{}
	resp, err := db.GetItem(&dynamodb.GetItemInput{
		TableName: aws.String(userTable),
		Key: map[string]*dynamodb.AttributeValue{
			"id": {
				S: aws.String(ID),
			},
		},
	})
	if err != nil {
		return user, err
	}
	if len(resp.Item) == 0 {
		return user, userNotFound
	}
	log.Println(resp)
	err = dynamodbattribute.Unmarshal(&dynamodb.AttributeValue{M: resp.Item}, &user)

Then I get:

`2018/04/27 18:28:36 UnmarshalTypeError: cannot unmarshal string into Go value of type kind.UserStatus

Put and Update has no issue with marshaling, I get errors only while unmarshalling.

Does it support enum in struct fields?

@zero-master
Copy link
Author

Solved by defining:

func (r UserStatus) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
	s, ok := _UserStatusValueToName[r]
	if !ok {
		return fmt.Errorf("invalid UserStatus: %d", r)
	}
	av.S = &s
	return nil
}

func (r *UserStatus) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
	s := *av.S
	v, ok := _UserStatusNameToValue[s]
	if !ok {
		return fmt.Errorf("invalid UserStatus %q", s)
	}
	*r = v
	return nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant