Skip to content

Commit 8e3d3cb

Browse files
committed
fix: json/encoding marshal errors of parameters with optional structs
Generated parameter structs have field tags omitempty and/or omitzero annotations: * omitempty for slices, maps and non-optional nullable fields * omitempty and omitzero for optional nullable fields * nothing for other fields
1 parent e772bdb commit 8e3d3cb

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

gen/_template/parameters.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
type {{ $op.Name }}Params struct {
2020
{{- range $p := $op.Params }}
2121
{{- template "godoc" $p.GoDoc }}
22-
{{ $p.Name }} {{ $p.Type.Go }}
22+
{{ $p.Name }} {{ $p.Type.Go }} {{ if $p.GoStructTag }}{{ backquote $p.GoStructTag }}{{ end }}
2323
{{- end }}
2424
}
2525

gen/ir/operation.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,31 @@ func (op Parameter) GoDoc() []string {
122122
return prettyDoc(s.Description, notice)
123123
}
124124

125+
// GoStructTag returns a Go struct tag for this parameter (if relevant).
126+
// Currently only returns emoempty of arrays, maps and nullable Type.GenericVariant,
127+
// and omitzero for parameters with optional Type.GenericVariant
128+
func (op Parameter) GoStructTag() string {
129+
if op.Type == nil {
130+
return ""
131+
}
132+
switch op.Type.Kind {
133+
case KindArray, KindMap:
134+
return `json:",omitempty"`
135+
default:
136+
return op.goStructTag()
137+
}
138+
}
139+
140+
func (op Parameter) goStructTag() string {
141+
variant := op.Type.GenericVariant
142+
if variant.OnlyNullable() {
143+
return `json:",omitempty"`
144+
} else if variant.Optional {
145+
return `json:",omitempty,omitzero"`
146+
}
147+
return ""
148+
}
149+
125150
// Default returns default value of this field, if it is set.
126151
func (op Parameter) Default() Default {
127152
var schema *jsonschema.Schema

go.mod

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
module github.com/ogen-go/ogen
22

3-
go 1.23.0
3+
go 1.24.0
44

5-
toolchain go1.23.7
5+
toolchain go1.24.1
66

77
require (
88
github.com/davecgh/go-spew v1.1.1

0 commit comments

Comments
 (0)