thriftgo icon indicating copy to clipboard operation
thriftgo copied to clipboard

Feature proposal: support getting enum annotation with function in generated code

Open DMwangnima opened this issue 10 months ago • 0 comments

Enum is represented as int64 in thriftgo, and each enumeration is mapped to the corresponding string. idl:

enum KitexEnum {
    ONE
    TWO
    THREE
}

generated code:

type KitexEnum int64

const (
	KitexEnum_ONE   KitexEnum = 0
	KitexEnum_TWO   KitexEnum = 1
	KitexEnum_THREE KitexEnum = 2
)

func (p KitexEnum) String() string {
	switch p {
	case KitexEnum_ONE:
		return "ONE"
	case KitexEnum_TWO:
		return "TWO"
	case KitexEnum_THREE:
		return "THREE"
	}
	return "<UNSET>"
}

But in some scenarios, the information represented by the string is a bit thin, so it needs to be annotated, as shown below:

enum KitexEnum {
    ONE (keya=val1)
    TWO (keyb=val2)
    THREE (keyc=val3)
}

Currently, the only way to get these enums at runtime is through thrift reflection, which is a long path and requires reflection to be enabled: https://github.com/cloudwego/thriftgo/blob/65c93f83f07f0c06797d6c80d3803539f064e0bb/thrift_reflection/descriptor.go#L5945

So we want to add GetAnnotation(key string) method to the Enum type when generating Enum code, so that we can quickly get the annotation value of an enum value. For instance:

var kitexEnum_Annotations = map[KitexEnum]map[string][]string{
	KitexEnum_ONE: map[string][]string{
		"keya": []string{"val1"},
	},
	KitexEnum_TWO: map[string][]string{
		"keyb": []string{"val2"},
	},
	KitexEnum_THREE: map[string][]string{
		"keyc": []string{"val3"},
	},
}

func (p KitexEnum) GetAnnotations(key string) []string {
	switch p {
	case KitexEnum_ONE:
		return kitexEnum_Annotations[KitexEnum_ONE][key]
	case KitexEnum_TWO:
		return kitexEnum_Annotations[KitexEnum_TWO][key]
	case KitexEnum_THREE:
		return kitexEnum_Annotations[KitexEnum_THREE][key]
	}
	return nil
}

If you are interested in implementing this feature, feel free to take~

DMwangnima avatar Apr 25 '24 10:04 DMwangnima