structs: add omitempty tag option

Doesn't add it to the final result if the field value is a zero value
This commit is contained in:
Fatih Arslan 2014-09-14 13:56:50 +03:00
parent 8624dc5ae3
commit 9c8bc21e6a

View File

@ -35,18 +35,29 @@ func New(s interface{}) *Struct {
// // Field appears in map as key "myName". // // Field appears in map as key "myName".
// Name string `structs:"myName"` // Name string `structs:"myName"`
// //
// A value with the content of "-" ignores that particular field. Example: // A tag value with the content of "-" ignores that particular field. Example:
// //
// // Field is ignored by this package. // // Field is ignored by this package.
// Field bool `structs:"-"` // Field bool `structs:"-"`
// //
// A value with the option of "omitnested" stops iterating further if the type // A tag value with the option of "omitnested" stops iterating further if the type
// is a struct. Example: // is a struct. Example:
// //
// // Field is not processed further by this package. // // Field is not processed further by this package.
// Field time.Time `structs:"myName,omitnested"` // Field time.Time `structs:"myName,omitnested"`
// Field *http.Request `structs:",omitnested"` // Field *http.Request `structs:",omitnested"`
// //
// A tag value with the option of "omitempty" ignores that particular field if
// the field value is empty. Example:
//
// // Field appears in map as key "myName", but the field is
// // skipped if empty.
// Field string `structs:"myName,omitempty"`
//
// // Field appears in map as key "Field" (the default), but
// // the field is skipped if empty.
// Field string `structs:",omitempty"`
//
// Note that only exported fields of a struct can be accessed, non exported // Note that only exported fields of a struct can be accessed, non exported
// fields will be neglected. // fields will be neglected.
func (s *Struct) Map() map[string]interface{} { func (s *Struct) Map() map[string]interface{} {
@ -65,6 +76,16 @@ func (s *Struct) Map() map[string]interface{} {
name = tagName name = tagName
} }
// if the value is a zero value do not include
if tagOpts.Has("omitempty") {
zero := reflect.Zero(val.Type()).Interface()
current := val.Interface()
if reflect.DeepEqual(current, zero) {
continue
}
}
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
// look out for embedded structs, and convert them to a // look out for embedded structs, and convert them to a
// map[string]interface{} too // map[string]interface{} too