File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -29,9 +29,10 @@ func Unmarshal(b []byte, v interface{}) error {
2929}
3030
3131type Encoder struct {
32- Order binary.ByteOrder
33- w io.Writer
34- buf []byte
32+ Order binary.ByteOrder
33+ w io.Writer
34+ buf []byte
35+ strict bool
3536}
3637
3738func NewEncoder (w io.Writer ) * Encoder {
@@ -42,6 +43,16 @@ func NewEncoder(w io.Writer) *Encoder {
4243 }
4344}
4445
46+ // NewStrictEncoder creates an encoder similar to NewEncoder, however
47+ // if this encoder attempts to encode a struct and the struct has no encodable
48+ // fields an error is returned whereas the encoder returned from NewEncoder
49+ // will simply not write anything to `w`.
50+ func NewStrictEncoder (w io.Writer ) * Encoder {
51+ e := NewEncoder (w )
52+ e .strict = true
53+ return e
54+ }
55+
4556func (e * Encoder ) writeVarint (v int ) error {
4657 l := binary .PutUvarint (e .buf , uint64 (v ))
4758 _ , err := e .w .Write (e .buf [:l ])
@@ -91,15 +102,20 @@ func (b *Encoder) Encode(v interface{}) (err error) {
91102
92103 case reflect .Struct :
93104 l := rv .NumField ()
105+ n := 0
94106 for i := 0 ; i < l ; i ++ {
95107 if v := rv .Field (i ); v .CanSet () && t .Field (i ).Name != "_" {
96108 // take the address of the field, so structs containing structs
97109 // are correctly encoded.
98110 if err = b .Encode (v .Addr ().Interface ()); err != nil {
99111 return
100112 }
113+ n ++
101114 }
102115 }
116+ if b .strict && n == 0 {
117+ return fmt .Errorf ("binary: struct had no encodable fields" )
118+ }
103119
104120 case reflect .Map :
105121 l := rv .Len ()
You can’t perform that action at this time.
0 commit comments