github.com/go-kivik/kivik/v4@v4.3.2/document.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 package kivik 14 15 import ( 16 "encoding/json" 17 ) 18 19 // document represents any CouchDB document. 20 type document struct { 21 ID string `json:"_id"` 22 Rev string `json:"_rev"` 23 Attachments *Attachments `json:"_attachments,omitempty"` 24 Data map[string]interface{} `json:"-"` 25 } 26 27 // MarshalJSON satisfies the json.Marshaler interface 28 func (d *document) MarshalJSON() ([]byte, error) { 29 var data []byte 30 doc, err := json.Marshal(*d) 31 if err != nil { 32 return nil, err 33 } 34 if len(d.Data) > 0 { 35 var err error 36 if data, err = json.Marshal(d.Data); err != nil { 37 return nil, err 38 } 39 doc[len(doc)-1] = ',' 40 return append(doc, data[1:]...), nil 41 } 42 return doc, nil 43 } 44 45 // UnmarshalJSON satisfies the json.Unmarshaler interface. 46 func (d *document) UnmarshalJSON(p []byte) error { 47 type internalDoc document 48 doc := &internalDoc{} 49 if err := json.Unmarshal(p, &doc); err != nil { 50 return err 51 } 52 data := make(map[string]interface{}) 53 if err := json.Unmarshal(p, &data); err != nil { 54 return err 55 } 56 delete(data, "_id") 57 delete(data, "_rev") 58 delete(data, "_attachments") 59 *d = document(*doc) 60 d.Data = data 61 return nil 62 }