Improved generated code by defining map outside of function.
This commit is contained in:
parent
40291a96dd
commit
dfe6af903e
35
template.go
35
template.go
@ -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())
|
||||
}
|
||||
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}}
|
||||
}
|
||||
|
||||
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 {
|
||||
|
Loading…
Reference in New Issue
Block a user