File: encoder_example_test.go

package info (click to toggle)
golang-mongodb-mongo-driver 1.17.1%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 25,988 kB
  • sloc: perl: 533; ansic: 491; python: 432; sh: 327; makefile: 174
file content (284 lines) | stat: -rw-r--r-- 6,803 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright (C) MongoDB, Inc. 2023-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

package bson_test

import (
	"bytes"
	"errors"
	"fmt"
	"io"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/bsonrw"
)

func ExampleEncoder() {
	// Create an Encoder that writes BSON values to a bytes.Buffer.
	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewBSONValueWriter(buf)
	if err != nil {
		panic(err)
	}
	encoder, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	type Product struct {
		Name  string `bson:"name"`
		SKU   string `bson:"sku"`
		Price int64  `bson:"price_cents"`
	}

	// Use the Encoder to marshal a BSON document that contains the name, SKU,
	// and price (in cents) of a product.
	product := Product{
		Name:  "Cereal Rounds",
		SKU:   "AB12345",
		Price: 399,
	}
	err = encoder.Encode(product)
	if err != nil {
		panic(err)
	}

	// Print the BSON document as Extended JSON by converting it to bson.Raw.
	fmt.Println(bson.Raw(buf.Bytes()).String())
	// Output: {"name": "Cereal Rounds","sku": "AB12345","price_cents": {"$numberLong":"399"}}
}

type CityState struct {
	City  string
	State string
}

func (k CityState) String() string {
	return fmt.Sprintf("%s, %s", k.City, k.State)
}

func ExampleEncoder_StringifyMapKeysWithFmt() {
	// Create an Encoder that writes BSON values to a bytes.Buffer.
	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewBSONValueWriter(buf)
	if err != nil {
		panic(err)
	}
	encoder, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	// Configure the Encoder to convert Go map keys to BSON document field names
	// using fmt.Sprintf instead of the default string conversion logic.
	encoder.StringifyMapKeysWithFmt()

	// Use the Encoder to marshal a BSON document that contains is a map of
	// city and state to a list of zip codes in that city.
	zipCodes := map[CityState][]int{
		{City: "New York", State: "NY"}: {10001, 10301, 10451},
	}
	err = encoder.Encode(zipCodes)
	if err != nil {
		panic(err)
	}

	// Print the BSON document as Extended JSON by converting it to bson.Raw.
	fmt.Println(bson.Raw(buf.Bytes()).String())
	// Output: {"New York, NY": [{"$numberInt":"10001"},{"$numberInt":"10301"},{"$numberInt":"10451"}]}
}

func ExampleEncoder_UseJSONStructTags() {
	// Create an Encoder that writes BSON values to a bytes.Buffer.
	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewBSONValueWriter(buf)
	if err != nil {
		panic(err)
	}
	encoder, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	type Product struct {
		Name  string `json:"name"`
		SKU   string `json:"sku"`
		Price int64  `json:"price_cents"`
	}

	// Configure the Encoder to use "json" struct tags when decoding if "bson"
	// struct tags are not present.
	encoder.UseJSONStructTags()

	// Use the Encoder to marshal a BSON document that contains the name, SKU,
	// and price (in cents) of a product.
	product := Product{
		Name:  "Cereal Rounds",
		SKU:   "AB12345",
		Price: 399,
	}
	err = encoder.Encode(product)
	if err != nil {
		panic(err)
	}

	// Print the BSON document as Extended JSON by converting it to bson.Raw.
	fmt.Println(bson.Raw(buf.Bytes()).String())
	// Output: {"name": "Cereal Rounds","sku": "AB12345","price_cents": {"$numberLong":"399"}}
}

func ExampleEncoder_multipleBSONDocuments() {
	// Create an Encoder that writes BSON values to a bytes.Buffer.
	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewBSONValueWriter(buf)
	if err != nil {
		panic(err)
	}
	encoder, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	type Coordinate struct {
		X int
		Y int
	}

	// Use the encoder to marshal 5 Coordinate values as a sequence of BSON
	// documents.
	for i := 0; i < 5; i++ {
		err := encoder.Encode(Coordinate{
			X: i,
			Y: i + 1,
		})
		if err != nil {
			panic(err)
		}
	}

	// Read each marshaled BSON document from the buffer and print them as
	// Extended JSON by converting them to bson.Raw.
	for {
		doc, err := bson.ReadDocument(buf)
		if errors.Is(err, io.EOF) {
			return
		}
		if err != nil {
			panic(err)
		}
		fmt.Println(doc.String())
	}
	// Output:
	// {"x": {"$numberInt":"0"},"y": {"$numberInt":"1"}}
	// {"x": {"$numberInt":"1"},"y": {"$numberInt":"2"}}
	// {"x": {"$numberInt":"2"},"y": {"$numberInt":"3"}}
	// {"x": {"$numberInt":"3"},"y": {"$numberInt":"4"}}
	// {"x": {"$numberInt":"4"},"y": {"$numberInt":"5"}}
}

func ExampleEncoder_extendedJSON() {
	// Create an Encoder that writes canonical Extended JSON values to a
	// bytes.Buffer.
	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false)
	if err != nil {
		panic(err)
	}
	encoder, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	type Product struct {
		Name  string `bson:"name"`
		SKU   string `bson:"sku"`
		Price int64  `bson:"price_cents"`
	}

	// Use the Encoder to marshal a BSON document that contains the name, SKU,
	// and price (in cents) of a product.
	product := Product{
		Name:  "Cereal Rounds",
		SKU:   "AB12345",
		Price: 399,
	}
	err = encoder.Encode(product)
	if err != nil {
		panic(err)
	}

	fmt.Println(buf.String())
	// Output: {"name":"Cereal Rounds","sku":"AB12345","price_cents":{"$numberLong":"399"}}
}

func ExampleEncoder_multipleExtendedJSONDocuments() {
	// Create an Encoder that writes canonical Extended JSON values to a
	// bytes.Buffer.
	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewExtJSONValueWriter(buf, true, false)
	if err != nil {
		panic(err)
	}
	encoder, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	type Coordinate struct {
		X int
		Y int
	}

	// Use the encoder to marshal 5 Coordinate values as a sequence of Extended
	// JSON documents.
	for i := 0; i < 5; i++ {
		err := encoder.Encode(Coordinate{
			X: i,
			Y: i + 1,
		})
		if err != nil {
			panic(err)
		}
	}

	fmt.Println(buf.String())
	// Output:
	// {"x":{"$numberInt":"0"},"y":{"$numberInt":"1"}}
	// {"x":{"$numberInt":"1"},"y":{"$numberInt":"2"}}
	// {"x":{"$numberInt":"2"},"y":{"$numberInt":"3"}}
	// {"x":{"$numberInt":"3"},"y":{"$numberInt":"4"}}
	// {"x":{"$numberInt":"4"},"y":{"$numberInt":"5"}}
}

func ExampleEncoder_IntMinSize() {
	// Create an encoder that will marshal integers as the minimum BSON int size
	// (either 32 or 64 bits) that can represent the integer value.
	type foo struct {
		Bar uint32
	}

	buf := new(bytes.Buffer)
	vw, err := bsonrw.NewBSONValueWriter(buf)
	if err != nil {
		panic(err)
	}

	enc, err := bson.NewEncoder(vw)
	if err != nil {
		panic(err)
	}

	enc.IntMinSize()

	err = enc.Encode(foo{2})
	if err != nil {
		panic(err)
	}

	fmt.Println(bson.Raw(buf.Bytes()).String())
	// Output:
	// {"bar": {"$numberInt":"2"}}
}