Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement "omitalways" tag to allow decode yet prevent encode. #390

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 18 additions & 10 deletions bson/bson.go
Original file line number Diff line number Diff line change
Expand Up @@ -552,6 +552,10 @@ func handleErr(err *error) {
// omitempty Only include the field if it's not set to the zero
// value for the type or to empty slices or maps.
//
// omitalways Never include the field. This is most useful for
// embedded structs that should be decoded, but never
// encoded.
//
// minsize Marshal an int64 value as an int32, if that's feasible
// while preserving the numeric value.
//
Expand All @@ -564,11 +568,12 @@ func handleErr(err *error) {
//
// type T struct {
// A bool
// B int "myb"
// C string "myc,omitempty"
// D string `bson:",omitempty" json:"jsonkey"`
// E int64 ",minsize"
// F int64 "myf,omitempty,minsize"
// B int "myb"
// C string "myc,omitempty"
// D string `bson:",omitempty" json:"jsonkey"`
// E int64 ",minsize"
// F int64 "myf,omitempty,minsize"
// G CustomType "myg,omitalways"
// }
//
func Marshal(in interface{}) (out []byte, err error) {
Expand Down Expand Up @@ -697,11 +702,12 @@ type structInfo struct {
}

type fieldInfo struct {
Key string
Num int
OmitEmpty bool
MinSize bool
Inline []int
Key string
Num int
OmitEmpty bool
OmitAlways bool
MinSize bool
Inline []int
}

var structMap = make(map[reflect.Type]*structInfo)
Expand Down Expand Up @@ -760,6 +766,8 @@ func getStructInfo(st reflect.Type) (*structInfo, error) {
switch strings.TrimSpace(flag) {
case "omitempty":
info.OmitEmpty = true
case "omitalways":
info.OmitAlways = true
case "minsize":
info.MinSize = true
case "inline":
Expand Down
3 changes: 3 additions & 0 deletions bson/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,9 @@ func (e *encoder) addStruct(v reflect.Value) {
if info.OmitEmpty && isZero(value) {
continue
}
if info.OmitAlways {
continue
}
if useRespectNilValues &&
(value.Kind() == reflect.Slice || value.Kind() == reflect.Map) &&
value.IsNil() {
Expand Down