From 9c8bc21e6a222e2d706e5e75a4097833f67c7702 Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Sun, 14 Sep 2014 13:56:50 +0300 Subject: [PATCH] structs: add omitempty tag option Doesn't add it to the final result if the field value is a zero value --- structs.go | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/structs.go b/structs.go index 637245f..b051c25 100644 --- a/structs.go +++ b/structs.go @@ -35,18 +35,29 @@ func New(s interface{}) *Struct { // // Field appears in map as key "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 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: // // // Field is not processed further by this package. // Field time.Time `structs:"myName,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 // fields will be neglected. func (s *Struct) Map() map[string]interface{} { @@ -65,6 +76,16 @@ func (s *Struct) Map() map[string]interface{} { 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") { // look out for embedded structs, and convert them to a // map[string]interface{} too