forked from webrpc/gen-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum.go.tmpl
47 lines (38 loc) · 917 Bytes
/
enum.go.tmpl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
{{- define "enum" -}}
{{- $enumName := .Name -}}
{{- $enumType := .EnumType -}}
type {{$enumName}} {{$enumType}}
const (
{{- range .Fields}}
{{$enumName}}_{{.Name}} {{$enumName}} = {{.Value}}
{{- end}}
)
var {{$enumName}}_name = map[{{$enumType}}]string{
{{- range .Fields}}
{{.Value}}: "{{.Name}}",
{{- end}}
}
var {{$enumName}}_value = map[string]{{$enumType}}{
{{- range .Fields}}
"{{.Name}}": {{.Value}},
{{- end}}
}
func (x {{$enumName}}) String() string {
return {{$enumName}}_name[{{$enumType}}(x)]
}
func (x {{$enumName}}) MarshalJSON() ([]byte, error) {
buf := bytes.NewBufferString(`"`)
buf.WriteString({{$enumName}}_name[{{$enumType}}(x)])
buf.WriteString(`"`)
return buf.Bytes(), nil
}
func (x *{{$enumName}}) UnmarshalJSON(b []byte) error {
var j string
err := json.Unmarshal(b, &j)
if err != nil {
return err
}
*x = {{$enumName}}({{$enumName}}_value[j])
return nil
}
{{- end -}}