I have the following PartnerType
"enum" struct in go:
// PartnerType enum
type PartnerType int
const (
// PartnerTypeUnknown should never happen
PartnerTypeUnknown PartnerType = iota
// PartnerTypeTest test
PartnerTypeTest
)
func (t PartnerType) String() string {
names := [...]string{
"UNKNOWN",
"TEST"}
if t < PartnerTypeUnknown || t > PartnerTypeTest {
return names[0]
}
return names[t]
}
// MarshalJSON for enum
func (t PartnerType) MarshalJSON() ([]byte, error) {
s := t.String()
return json.Marshal(s)
}
// UnmarshalJSON for enum
func (t *PartnerType) UnmarshalJSON(b []byte) error {
*t = PartnerTypeUnknown
return nil
}
// MarshalText implements the text marshaller method
func (t *PartnerType) MarshalText() ([]byte, error) {
return []byte(t.String()), nil
}
// UnmarshalText implements the text unmarshaller method
func (t *PartnerType) UnmarshalText(text []byte) error {
*t = PartnerTypeUnknown
return nil
}
// Partner entity
type Partner struct {
ID string `dynamodbav:"PK,omitempty"`
Foo string `dynamodbav:"SK,omitempty"`
PartnerType PartnerType `dynamodbav:",omitempty,string"`
}
When doing a dynamodbattribute.MarshalMap()
I'd like my PartnerType
to be stored as a string. The dynamodbav struct tag allows you to store an int as a string (dynamodbav:",omitempty,string"
) however it is not calling my defined .String()
or Marshal/Unmarshal
implementations.
Said another way, it stores PartnerTypeTest
as "1"
not "TEST"
.
How can this be done?
For dynamodb you can implement your marshaler/unmarshaler for enums
Try the following:
// MarshalDynamoDBAttributeValue for ddb
func (t PartnerType) MarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
s := t.String()
av.S = &s
return nil
}
// UnmarshalDynamoDBAttributeValue implements the Unmarshaler interface
func (t *PartnerType) UnmarshalDynamoDBAttributeValue(av *dynamodb.AttributeValue) error {
// val := aws.StringValue(av.S)
*t = PartnerTypeUnknown
return nil
}