Invalid Struct Tag
ID |
go.invalid_struct_tag |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, suspicious |
Description
Reports a struct field tag whose string is malformed against the Go convention of
space-separated key:"value" pairs. Two clear defects are flagged: a quoted value whose
option list ends in a trailing comma (json:"name,omitempty,"), and a key whose value is
not wrapped in double quotes (xml:no_quotes).
Rationale
The reflect-based tag readers in encoding/json, encoding/xml and similar packages parse
field tags leniently: a malformed tag is silently ignored rather than rejected. The field is
then serialized under its default name and the intended directive (the JSON key, omitempty,
the XML attribute flag) is quietly lost. Because nothing fails to compile, the bug surfaces
only as wrong output at runtime.
type user struct {
Name string `json:"name,omitempty,"` // FLAW — trailing comma in the option list
Email string `xml:no_quotes` // FLAW — value is not double-quoted
Age int `json:"age,omitempty"` // OK
}
Remediation
Fix the tag to the key:"value" form. Remove the trailing comma from the option list and
wrap every value in double quotes. To use the field name with options, leave the name empty
(json:",omitempty"), which is valid.