Improved generated code by defining map outside of function.

This commit is contained in:
Francesc Campoy 2015-02-04 13:38:28 +00:00
parent 40291a96dd
commit dfe6af903e

View File

@ -20,32 +20,39 @@ import (
{{range $typename, $values := .TypesAndValues}}
func (r {{$typename}}) MarshalJSON() ([]byte, error) {
if s, ok := interface{}(r).(fmt.Stringer); ok {
return json.Marshal(s.String())
var (
_{{$typename}}NameToValue = map[string]{{$typename}} {
{{range $values}}"{{.}}": {{.}},
{{end}}
}
s, ok := map[{{$typename}}]string {
{{range $values}}{{.}}: "{{.}}",{{end}}
}[r]
if !ok {
return nil, fmt.Errorf("invalid {{$typename}}: %d", r)
}
return json.Marshal(s)
}
var _{{$typename}}NameToValue = map[string]{{$typename}} {
{{range $values}}"{{.}}": {{.}},{{end}}
}
_{{$typename}}ValueToName = map[{{$typename}}]string {
{{range $values}}{{.}}: "{{.}}",
{{end}}
}
)
func init() {
var v {{$typename}}
if _, ok := interface{}(v).(fmt.Stringer); ok {
_{{$typename}}NameToValue = map[string]{{$typename}} {
{{range $values}}interface{}({{.}}).(fmt.Stringer).String(): {{.}},{{end}}
{{range $values}}interface{}({{.}}).(fmt.Stringer).String(): {{.}},
{{end}}
}
}
}
func (r {{$typename}}) MarshalJSON() ([]byte, error) {
if s, ok := interface{}(r).(fmt.Stringer); ok {
return json.Marshal(s.String())
}
s, ok := _{{$typename}}ValueToName[r]
if !ok {
return nil, fmt.Errorf("invalid {{$typename}}: %d", r)
}
return json.Marshal(s)
}
func (r *{{$typename}}) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {