|
5 | 5 | - [CommentStart](#commentstart) - Ensures comments start with the serialized form of the type |
6 | 6 | - [ConflictingMarkers](#conflictingmarkers) - Detects mutually exclusive markers on the same field |
7 | 7 | - [DefaultOrRequired](#defaultorrequired) - Ensures fields marked as required do not have default values |
| 8 | +- [Defaults](#defaults) - Checks that fields with default markers are configured correctly |
8 | 9 | - [DuplicateMarkers](#duplicatemarkers) - Checks for exact duplicates of markers |
9 | 10 | - [DependentTags](#dependenttags) - Enforces dependencies between markers |
10 | 11 | - [ForbiddenMarkers](#forbiddenmarkers) - Checks that no forbidden markers are present on types/fields. |
@@ -212,6 +213,45 @@ The linter also detects conflicts with: |
212 | 213 |
|
213 | 214 | This linter is enabled by default and helps ensure that API designs are consistent and unambiguous about whether fields are truly required or have default values. |
214 | 215 |
|
| 216 | +## Defaults |
| 217 | + |
| 218 | +The `defaults` linter checks that fields with default markers are configured correctly. |
| 219 | + |
| 220 | +Fields with default markers (`+default`, `+kubebuilder:default`, or `+k8s:default`) should also be marked as optional. |
| 221 | +Additionally, fields with default markers should have `omitempty` or `omitzero` in their json tags to ensure that |
| 222 | +the default values are applied correctly during serialization and deserialization. |
| 223 | + |
| 224 | +### Example |
| 225 | + |
| 226 | +A well-configured field with a default: |
| 227 | + |
| 228 | +```go |
| 229 | +type MyStruct struct { |
| 230 | + // +optional |
| 231 | + // +default="default-value" |
| 232 | + Field string `json:"field,omitempty"` |
| 233 | +} |
| 234 | +``` |
| 235 | + |
| 236 | +The following issues will be flagged by the linter: |
| 237 | + |
| 238 | +```go |
| 239 | +type MyStruct struct { |
| 240 | + // Missing optional marker |
| 241 | + // +default="value" |
| 242 | + Field1 string `json:"field1,omitempty"` // Error: has default but not marked as optional |
| 243 | + |
| 244 | + // Missing omitempty tag |
| 245 | + // +optional |
| 246 | + // +default="value" |
| 247 | + Field2 string `json:"field2"` // Error: has default but no omitempty or omitzero |
| 248 | +} |
| 249 | +``` |
| 250 | + |
| 251 | +### Fixes |
| 252 | + |
| 253 | +The `defaults` linter can automatically add `omitempty,omitzero` to the json tag when missing. |
| 254 | + |
215 | 255 | ## DuplicateMarkers |
216 | 256 |
|
217 | 257 | The duplicatemarkers linter checks for exact duplicates of markers for types and fields. |
|
0 commit comments