| 1 |
{{ $u := . }} |
| 2 |
{{ $basename := $u.Name.Go }} |
| 3 |
{{ $discriminatorField := $u.DiscriminatorField API }} |
| 4 |
|
| 5 |
// {{ $u.Name }} -> {{ $basename }} (flat union) |
| 6 |
|
| 7 |
// {{ $basename }} implements the "{{ .Name }}" QMP API type. |
| 8 |
// |
| 9 |
// Can be one of: |
| 10 |
{{- range $suffix, $type := $u.Options }} |
| 11 |
// - {{ $basename }}{{ $suffix.Go }} |
| 12 |
{{- end }} |
| 13 |
type {{ $basename }} interface { |
| 14 |
is{{ $basename }}() |
| 15 |
} |
| 16 |
|
| 17 |
{{- range $suffix, $type := $u.Options }} |
| 18 |
{{ $subname := printf "%s%s" $basename $suffix.Go }} |
| 19 |
{{ $subtype := (index API $type) }} |
| 20 |
|
| 21 |
// {{ $subname }} is an implementation of {{ $basename }}. |
| 22 |
type {{ $subname }} struct { |
| 23 |
{{- range $u.Base.Fields API }} |
| 24 |
{{- if ne .Name $u.Discriminator }} |
| 25 |
{{ render . }} |
| 26 |
{{- end }} |
| 27 |
{{- end }} |
| 28 |
{{- range $subtype.Fields }} |
| 29 |
{{ render . }} |
| 30 |
{{- end }} |
| 31 |
} |
| 32 |
|
| 33 |
func ({{ $subname }}) is{{ $basename }}() {} |
| 34 |
|
| 35 |
// MarshalJSON implements json.Marshaler. |
| 36 |
func (s {{ $subname }}) MarshalJSON() ([]byte, error) { |
| 37 |
v := struct{ |
| 38 |
{{- range $u.Base.Fields API }} |
| 39 |
{{- if eq .Name $u.Discriminator }} |
| 40 |
{{ render . }} |
| 41 |
{{- end }} |
| 42 |
{{- end }} |
| 43 |
{{ $subname }} |
| 44 |
}{ |
| 45 |
{{ $discriminatorField.Type.Go }}{{ $suffix.Go }}, |
| 46 |
s, |
| 47 |
} |
| 48 |
return json.Marshal(v) |
| 49 |
} |
| 50 |
{{- end }} |
| 51 |
|
| 52 |
func decode{{ $basename }}(bs json.RawMessage) ({{ $basename }}, error) { |
| 53 |
v := struct{ |
| 54 |
{{ render $discriminatorField }} |
| 55 |
}{} |
| 56 |
if err := json.Unmarshal([]byte(bs), &v); err != nil { |
| 57 |
return nil, err |
| 58 |
} |
| 59 |
switch v.{{ $discriminatorField.Name.Go }} { |
| 60 |
{{- range $suffix, $type := $u.Options }} |
| 61 |
case {{ $discriminatorField.Type.Go }}{{ $suffix.Go }}: |
| 62 |
var ret {{ $basename }}{{ $suffix.Go }} |
| 63 |
err := json.Unmarshal([]byte(bs), &ret) |
| 64 |
return ret, err |
| 65 |
{{- end }} |
| 66 |
default: |
| 67 |
return nil, fmt.Errorf("unknown flat union subtype %q for flat union {{ $basename }}", v.{{ $discriminatorField.Name.Go }}) |
| 68 |
} |
| 69 |
} |