Debian Codegraph @

pkg/internal/third_party/go-json-experiment/json/example_test.go

raw
1 // Copyright 2022 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package json_test
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11 "log"
12 "math"
13 "net/http"
14 "net/netip"
15 "os"
16 "reflect"
17 "strconv"
18 "strings"
19 "sync/atomic"
20 "time"
21
22 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json"
23 "k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/jsontext"
24 )
25
26 // If a type implements [encoding.TextMarshaler] and/or [encoding.TextUnmarshaler],
27 // then the MarshalText and UnmarshalText methods are used to encode/decode
28 // the value to/from a JSON string.
29 func Example_textMarshal() {
30 // Round-trip marshal and unmarshal a hostname map where the netip.Addr type
31 // implements both encoding.TextMarshaler and encoding.TextUnmarshaler.
32 want := map[netip.Addr]string{
33 netip.MustParseAddr("192.168.0.100"): "carbonite",
34 netip.MustParseAddr("192.168.0.101"): "obsidian",
35 netip.MustParseAddr("192.168.0.102"): "diamond",
36 }
37 b, err := json.Marshal(&want, json.Deterministic(true))
38 if err != nil {
39 log.Fatal(err)
40 }
41 var got map[netip.Addr]string
42 err = json.Unmarshal(b, &got)
43 if err != nil {
44 log.Fatal(err)
45 }
46
47 // Sanity check.
48 if !reflect.DeepEqual(got, want) {
49 log.Fatalf("roundtrip mismatch: got %v, want %v", got, want)
50 }
51
52 // Print the serialized JSON object.
53 (*jsontext.Value)(&b).Indent() // indent for readability
54 fmt.Println(string(b))
55
56 // Output:
57 // {
58 // "192.168.0.100": "carbonite",
59 // "192.168.0.101": "obsidian",
60 // "192.168.0.102": "diamond"
61 // }
62 }
63
64 // By default, JSON object names for Go struct fields are derived from
65 // the Go field name, but may be specified in the `json` tag.
66 // Due to JSON's heritage in JavaScript, the most common naming convention
67 // used for JSON object names is camelCase.
68 func Example_fieldNames() {
69 var value struct {
70 // This field is explicitly ignored with the special "-" name.
71 Ignored any `json:"-"`
72 // No JSON name is not provided, so the Go field name is used.
73 GoName any
74 // A JSON name is provided without any special characters.
75 JSONName any `json:"jsonName"`
76 // No JSON name is not provided, so the Go field name is used.
77 Option any `json:",case:ignore"`
78 // An empty JSON name specified using an single-quoted string literal.
79 Empty any `json:"''"`
80 // A dash JSON name specified using an single-quoted string literal.
81 Dash any `json:"'-'"`
82 // A comma JSON name specified using an single-quoted string literal.
83 Comma any `json:"','"`
84 // JSON name with quotes specified using a single-quoted string literal.
85 Quote any `json:"'\"\\''"`
86 // An unexported field is always ignored.
87 unexported any
88 }
89
90 b, err := json.Marshal(value)
91 if err != nil {
92 log.Fatal(err)
93 }
94 (*jsontext.Value)(&b).Indent() // indent for readability
95 fmt.Println(string(b))
96
97 // Output:
98 // {
99 // "GoName": null,
100 // "jsonName": null,
101 // "Option": null,
102 // "": null,
103 // "-": null,
104 // ",": null,
105 // "\"'": null
106 // }
107 }
108
109 // Unmarshal matches JSON object names with Go struct fields using
110 // a case-sensitive match, but can be configured to use a case-insensitive
111 // match with the "case:ignore" option. This permits unmarshaling from inputs
112 // that use naming conventions such as camelCase, snake_case, or kebab-case.
113 func Example_caseSensitivity() {
114 // JSON input using various naming conventions.
115 const input = `[
116 {"firstname": true},
117 {"firstName": true},
118 {"FirstName": true},
119 {"FIRSTNAME": true},
120 {"first_name": true},
121 {"FIRST_NAME": true},
122 {"first-name": true},
123 {"FIRST-NAME": true},
124 {"unknown": true}
125 ]`
126
127 // Without "case:ignore", Unmarshal looks for an exact match.
128 var caseStrict []struct {
129 X bool `json:"firstName"`
130 }
131 if err := json.Unmarshal([]byte(input), &caseStrict); err != nil {
132 log.Fatal(err)
133 }
134 fmt.Println(caseStrict) // exactly 1 match found
135
136 // With "case:ignore", Unmarshal looks first for an exact match,
137 // then for a case-insensitive match if none found.
138 var caseIgnore []struct {
139 X bool `json:"firstName,case:ignore"`
140 }
141 if err := json.Unmarshal([]byte(input), &caseIgnore); err != nil {
142 log.Fatal(err)
143 }
144 fmt.Println(caseIgnore) // 8 matches found
145
146 // Output:
147 // [{false} {true} {false} {false} {false} {false} {false} {false} {false}]
148 // [{true} {true} {true} {true} {true} {true} {true} {true} {false}]
149 }
150
151 // Go struct fields can be omitted from the output depending on either
152 // the input Go value or the output JSON encoding of the value.
153 // The "omitzero" option omits a field if it is the zero Go value or
154 // implements a "IsZero() bool" method that reports true.
155 // The "omitempty" option omits a field if it encodes as an empty JSON value,
156 // which we define as a JSON null or empty JSON string, object, or array.
157 // In many cases, the behavior of "omitzero" and "omitempty" are equivalent.
158 // If both provide the desired effect, then using "omitzero" is preferred.
159 func Example_omitFields() {
160 type MyStruct struct {
161 Foo string `json:",omitzero"`
162 Bar []int `json:",omitempty"`
163 // Both "omitzero" and "omitempty" can be specified together,
164 // in which case the field is omitted if either would take effect.
165 // This omits the Baz field either if it is a nil pointer or
166 // if it would have encoded as an empty JSON object.
167 Baz *MyStruct `json:",omitzero,omitempty"`
168 }
169
170 // Demonstrate behavior of "omitzero".
171 b, err := json.Marshal(struct {
172 Bool bool `json:",omitzero"`
173 Int int `json:",omitzero"`
174 String string `json:",omitzero"`
175 Time time.Time `json:",omitzero"`
176 Addr netip.Addr `json:",omitzero"`
177 Struct MyStruct `json:",omitzero"`
178 SliceNil []int `json:",omitzero"`
179 Slice []int `json:",omitzero"`
180 MapNil map[int]int `json:",omitzero"`
181 Map map[int]int `json:",omitzero"`
182 PointerNil *string `json:",omitzero"`
183 Pointer *string `json:",omitzero"`
184 InterfaceNil any `json:",omitzero"`
185 Interface any `json:",omitzero"`
186 }{
187 // Bool is omitted since false is the zero value for a Go bool.
188 Bool: false,
189 // Int is omitted since 0 is the zero value for a Go int.
190 Int: 0,
191 // String is omitted since "" is the zero value for a Go string.
192 String: "",
193 // Time is omitted since time.Time.IsZero reports true.
194 Time: time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC),
195 // Addr is omitted since netip.Addr{} is the zero value for a Go struct.
196 Addr: netip.Addr{},
197 // Struct is NOT omitted since it is not the zero value for a Go struct.
198 Struct: MyStruct{Bar: []int{}, Baz: new(MyStruct)},
199 // SliceNil is omitted since nil is the zero value for a Go slice.
200 SliceNil: nil,
201 // Slice is NOT omitted since []int{} is not the zero value for a Go slice.
202 Slice: []int{},
203 // MapNil is omitted since nil is the zero value for a Go map.
204 MapNil: nil,
205 // Map is NOT omitted since map[int]int{} is not the zero value for a Go map.
206 Map: map[int]int{},
207 // PointerNil is omitted since nil is the zero value for a Go pointer.
208 PointerNil: nil,
209 // Pointer is NOT omitted since new(string) is not the zero value for a Go pointer.
210 Pointer: new(string),
211 // InterfaceNil is omitted since nil is the zero value for a Go interface.
212 InterfaceNil: nil,
213 // Interface is NOT omitted since (*string)(nil) is not the zero value for a Go interface.
214 Interface: (*string)(nil),
215 })
216 if err != nil {
217 log.Fatal(err)
218 }
219 (*jsontext.Value)(&b).Indent() // indent for readability
220 fmt.Println("OmitZero:", string(b)) // outputs "Struct", "Slice", "Map", "Pointer", and "Interface"
221
222 // Demonstrate behavior of "omitempty".
223 b, err = json.Marshal(struct {
224 Bool bool `json:",omitempty"`
225 Int int `json:",omitempty"`
226 String string `json:",omitempty"`
227 Time time.Time `json:",omitempty"`
228 Addr netip.Addr `json:",omitempty"`
229 Struct MyStruct `json:",omitempty"`
230 Slice []int `json:",omitempty"`
231 Map map[int]int `json:",omitempty"`
232 PointerNil *string `json:",omitempty"`
233 Pointer *string `json:",omitempty"`
234 InterfaceNil any `json:",omitempty"`
235 Interface any `json:",omitempty"`
236 }{
237 // Bool is NOT omitted since false is not an empty JSON value.
238 Bool: false,
239 // Int is NOT omitted since 0 is not a empty JSON value.
240 Int: 0,
241 // String is omitted since "" is an empty JSON string.
242 String: "",
243 // Time is NOT omitted since this encodes as a non-empty JSON string.
244 Time: time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC),
245 // Addr is omitted since this encodes as an empty JSON string.
246 Addr: netip.Addr{},
247 // Struct is omitted since {} is an empty JSON object.
248 Struct: MyStruct{Bar: []int{}, Baz: new(MyStruct)},
249 // Slice is omitted since [] is an empty JSON array.
250 Slice: []int{},
251 // Map is omitted since {} is an empty JSON object.
252 Map: map[int]int{},
253 // PointerNil is omitted since null is an empty JSON value.
254 PointerNil: nil,
255 // Pointer is omitted since "" is an empty JSON string.
256 Pointer: new(string),
257 // InterfaceNil is omitted since null is an empty JSON value.
258 InterfaceNil: nil,
259 // Interface is omitted since null is an empty JSON value.
260 Interface: (*string)(nil),
261 })
262 if err != nil {
263 log.Fatal(err)
264 }
265 (*jsontext.Value)(&b).Indent() // indent for readability
266 fmt.Println("OmitEmpty:", string(b)) // outputs "Bool", "Int", and "Time"
267
268 // Output:
269 // OmitZero: {
270 // "Struct": {},
271 // "Slice": [],
272 // "Map": {},
273 // "Pointer": "",
274 // "Interface": null
275 // }
276 // OmitEmpty: {
277 // "Bool": false,
278 // "Int": 0,
279 // "Time": "0001-01-01T00:00:00Z"
280 // }
281 }
282
283 // JSON objects can be inlined within a parent object similar to
284 // how Go structs can be embedded within a parent struct.
285 // The inlining rules are similar to those of Go embedding,
286 // but operates upon the JSON namespace.
287 func Example_inlinedFields() {
288 // Base is embedded within Container.
289 type Base struct {
290 // ID is promoted into the JSON object for Container.
291 ID string
292 // Type is ignored due to presence of Container.Type.
293 Type string
294 // Time cancels out with Container.Inlined.Time.
295 Time time.Time
296 }
297 // Other is embedded within Container.
298 type Other struct{ Cost float64 }
299 // Container embeds Base and Other.
300 type Container struct {
301 // Base is an embedded struct and is implicitly JSON inlined.
302 Base
303 // Type takes precedence over Base.Type.
304 Type int
305 // Inlined is a named Go field, but is explicitly JSON inlined.
306 Inlined struct {
307 // User is promoted into the JSON object for Container.
308 User string
309 // Time cancels out with Base.Time.
310 Time string
311 } `json:",inline"`
312 // ID does not conflict with Base.ID since the JSON name is different.
313 ID string `json:"uuid"`
314 // Other is not JSON inlined since it has an explicit JSON name.
315 Other `json:"other"`
316 }
317
318 // Format an empty Container to show what fields are JSON serializable.
319 var input Container
320 b, err := json.Marshal(&input)
321 if err != nil {
322 log.Fatal(err)
323 }
324 (*jsontext.Value)(&b).Indent() // indent for readability
325 fmt.Println(string(b))
326
327 // Output:
328 // {
329 // "ID": "",
330 // "Type": 0,
331 // "User": "",
332 // "uuid": "",
333 // "other": {
334 // "Cost": 0
335 // }
336 // }
337 }
338
339 // Due to version skew, the set of JSON object members known at compile-time
340 // may differ from the set of members encountered at execution-time.
341 // As such, it may be useful to have finer grain handling of unknown members.
342 // This package supports preserving, rejecting, or discarding such members.
343 func Example_unknownMembers() {
344 const input = `{
345 "Name": "Teal",
346 "Value": "#008080",
347 "WebSafe": false
348 }`
349 type Color struct {
350 Name string
351 Value string
352
353 // Unknown is a Go struct field that holds unknown JSON object members.
354 // It is marked as having this behavior with the "unknown" tag option.
355 //
356 // The type may be a jsontext.Value or map[string]T.
357 Unknown jsontext.Value `json:",unknown"`
358 }
359
360 // By default, unknown members are stored in a Go field marked as "unknown"
361 // or ignored if no such field exists.
362 var color Color
363 err := json.Unmarshal([]byte(input), &color)
364 if err != nil {
365 log.Fatal(err)
366 }
367 fmt.Println("Unknown members:", string(color.Unknown))
368
369 // Specifying RejectUnknownMembers causes Unmarshal
370 // to reject the presence of any unknown members.
371 err = json.Unmarshal([]byte(input), new(Color), json.RejectUnknownMembers(true))
372 var serr *json.SemanticError
373 if errors.As(err, &serr) && serr.Err == json.ErrUnknownName {
374 fmt.Println("Unmarshal error:", serr.Err, strconv.Quote(serr.JSONPointer.LastToken()))
375 }
376
377 // By default, Marshal preserves unknown members stored in
378 // a Go struct field marked as "unknown".
379 b, err := json.Marshal(color)
380 if err != nil {
381 log.Fatal(err)
382 }
383 fmt.Println("Output with unknown members: ", string(b))
384
385 // Specifying DiscardUnknownMembers causes Marshal
386 // to discard any unknown members.
387 b, err = json.Marshal(color, json.DiscardUnknownMembers(true))
388 if err != nil {
389 log.Fatal(err)
390 }
391 fmt.Println("Output without unknown members:", string(b))
392
393 // Output:
394 // Unknown members: {"WebSafe":false}
395 // Unmarshal error: unknown object member name "WebSafe"
396 // Output with unknown members: {"Name":"Teal","Value":"#008080","WebSafe":false}
397 // Output without unknown members: {"Name":"Teal","Value":"#008080"}
398 }
399
400 // The "format" tag option can be used to alter the formatting of certain types.
401 func Example_formatFlags() {
402 value := struct {
403 BytesBase64 []byte `json:",format:base64"`
404 BytesHex [8]byte `json:",format:hex"`
405 BytesArray []byte `json:",format:array"`
406 FloatNonFinite float64 `json:",format:nonfinite"`
407 MapEmitNull map[string]any `json:",format:emitnull"`
408 SliceEmitNull []any `json:",format:emitnull"`
409 TimeDateOnly time.Time `json:",format:'2006-01-02'"`
410 TimeUnixSec time.Time `json:",format:unix"`
411 DurationSecs time.Duration `json:",format:sec"`
412 DurationNanos time.Duration `json:",format:nano"`
413 DurationISO8601 time.Duration `json:",format:iso8601"`
414 }{
415 BytesBase64: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
416 BytesHex: [8]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
417 BytesArray: []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef},
418 FloatNonFinite: math.NaN(),
419 MapEmitNull: nil,
420 SliceEmitNull: nil,
421 TimeDateOnly: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
422 TimeUnixSec: time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC),
423 DurationSecs: 12*time.Hour + 34*time.Minute + 56*time.Second + 7*time.Millisecond + 8*time.Microsecond + 9*time.Nanosecond,
424 DurationNanos: 12*time.Hour + 34*time.Minute + 56*time.Second + 7*time.Millisecond + 8*time.Microsecond + 9*time.Nanosecond,
425 DurationISO8601: 12*time.Hour + 34*time.Minute + 56*time.Second + 7*time.Millisecond + 8*time.Microsecond + 9*time.Nanosecond,
426 }
427
428 b, err := json.Marshal(&value)
429 if err != nil {
430 log.Fatal(err)
431 }
432 (*jsontext.Value)(&b).Indent() // indent for readability
433 fmt.Println(string(b))
434
435 // Output:
436 // {
437 // "BytesBase64": "ASNFZ4mrze8=",
438 // "BytesHex": "0123456789abcdef",
439 // "BytesArray": [
440 // 1,
441 // 35,
442 // 69,
443 // 103,
444 // 137,
445 // 171,
446 // 205,
447 // 239
448 // ],
449 // "FloatNonFinite": "NaN",
450 // "MapEmitNull": null,
451 // "SliceEmitNull": null,
452 // "TimeDateOnly": "2000-01-01",
453 // "TimeUnixSec": 946684800,
454 // "DurationSecs": 45296.007008009,
455 // "DurationNanos": 45296007008009,
456 // "DurationISO8601": "PT12H34M56.007008009S"
457 // }
458 }
459
460 // When implementing HTTP endpoints, it is common to be operating with an
461 // [io.Reader] and an [io.Writer]. The [MarshalWrite] and [UnmarshalRead] functions
462 // assist in operating on such input/output types.
463 // [UnmarshalRead] reads the entirety of the [io.Reader] to ensure that [io.EOF]
464 // is encountered without any unexpected bytes after the top-level JSON value.
465 func Example_serveHTTP() {
466 // Some global state maintained by the server.
467 var n int64
468
469 // The "add" endpoint accepts a POST request with a JSON object
470 // containing a number to atomically add to the server's global counter.
471 // It returns the updated value of the counter.
472 http.HandleFunc("/api/add", func(w http.ResponseWriter, r *http.Request) {
473 // Unmarshal the request from the client.
474 var val struct{ N int64 }
475 if err := json.UnmarshalRead(r.Body, &val); err != nil {
476 // Inability to unmarshal the input suggests a client-side problem.
477 http.Error(w, err.Error(), http.StatusBadRequest)
478 return
479 }
480
481 // Marshal a response from the server.
482 val.N = atomic.AddInt64(&n, val.N)
483 if err := json.MarshalWrite(w, &val); err != nil {
484 // Inability to marshal the output suggests a server-side problem.
485 // This error is not always observable by the client since
486 // json.MarshalWrite may have already written to the output.
487 http.Error(w, err.Error(), http.StatusInternalServerError)
488 return
489 }
490 })
491 }
492
493 // Some Go types have a custom JSON representation where the implementation
494 // is delegated to some external package. Consequently, the "json" package
495 // will not know how to use that external implementation.
496 // For example, the [google.golang.org/protobuf/encoding/protojson] package
497 // implements JSON for all [google.golang.org/protobuf/proto.Message] types.
498 // [WithMarshalers] and [WithUnmarshalers] can be used
499 // to configure "json" and "protojson" to cooperate together.
500 func Example_protoJSON() {
501 // Let protoMessage be "google.golang.org/protobuf/proto".Message.
502 type protoMessage interface{ ProtoReflect() }
503 // Let foopbMyMessage be a concrete implementation of proto.Message.
504 type foopbMyMessage struct{ protoMessage }
505 // Let protojson be an import of "google.golang.org/protobuf/encoding/protojson".
506 var protojson struct {
507 Marshal func(protoMessage) ([]byte, error)
508 Unmarshal func([]byte, protoMessage) error
509 }
510
511 // This value mixes both non-proto.Message types and proto.Message types.
512 // It should use the "json" package to handle non-proto.Message types and
513 // should use the "protojson" package to handle proto.Message types.
514 var value struct {
515 // GoStruct does not implement proto.Message and
516 // should use the default behavior of the "json" package.
517 GoStruct struct {
518 Name string
519 Age int
520 }
521
522 // ProtoMessage implements proto.Message and
523 // should be handled using protojson.Marshal.
524 ProtoMessage *foopbMyMessage
525 }
526
527 // Marshal using protojson.Marshal for proto.Message types.
528 b, err := json.Marshal(&value,
529 // Use protojson.Marshal as a type-specific marshaler.
530 json.WithMarshalers(json.MarshalFunc(protojson.Marshal)))
531 if err != nil {
532 log.Fatal(err)
533 }
534
535 // Unmarshal using protojson.Unmarshal for proto.Message types.
536 err = json.Unmarshal(b, &value,
537 // Use protojson.Unmarshal as a type-specific unmarshaler.
538 json.WithUnmarshalers(json.UnmarshalFunc(protojson.Unmarshal)))
539 if err != nil {
540 log.Fatal(err)
541 }
542 }
543
544 // Many error types are not serializable since they tend to be Go structs
545 // without any exported fields (e.g., errors constructed with [errors.New]).
546 // Some applications, may desire to marshal an error as a JSON string
547 // even if these errors cannot be unmarshaled.
548 func ExampleWithMarshalers_errors() {
549 // Response to serialize with some Go errors encountered.
550 response := []struct {
551 Result string `json:",omitzero"`
552 Error error `json:",omitzero"`
553 }{
554 {Result: "Oranges are a good source of Vitamin C."},
555 {Error: &strconv.NumError{Func: "ParseUint", Num: "-1234", Err: strconv.ErrSyntax}},
556 {Error: &os.PathError{Op: "ReadFile", Path: "/path/to/secret/file", Err: os.ErrPermission}},
557 }
558
559 b, err := json.Marshal(&response,
560 // Intercept every attempt to marshal an error type.
561 json.WithMarshalers(json.JoinMarshalers(
562 // Suppose we consider strconv.NumError to be a safe to serialize:
563 // this type-specific marshal function intercepts this type
564 // and encodes the error message as a JSON string.
565 json.MarshalToFunc(func(enc *jsontext.Encoder, err *strconv.NumError) error {
566 return enc.WriteToken(jsontext.String(err.Error()))
567 }),
568 // Error messages may contain sensitive information that may not
569 // be appropriate to serialize. For all errors not handled above,
570 // report some generic error message.
571 json.MarshalFunc(func(error) ([]byte, error) {
572 return []byte(`"internal server error"`), nil
573 }),
574 )),
575 jsontext.Multiline(true)) // expand for readability
576 if err != nil {
577 log.Fatal(err)
578 }
579 fmt.Println(string(b))
580
581 // Output:
582 // [
583 // {
584 // "Result": "Oranges are a good source of Vitamin C."
585 // },
586 // {
587 // "Error": "strconv.ParseUint: parsing \"-1234\": invalid syntax"
588 // },
589 // {
590 // "Error": "internal server error"
591 // }
592 // ]
593 }
594
595 // In some applications, the exact precision of JSON numbers needs to be
596 // preserved when unmarshaling. This can be accomplished using a type-specific
597 // unmarshal function that intercepts all any types and pre-populates the
598 // interface value with a [jsontext.Value], which can represent a JSON number exactly.
599 func ExampleWithUnmarshalers_rawNumber() {
600 // Input with JSON numbers beyond the representation of a float64.
601 const input = `[false, 1e-1000, 3.141592653589793238462643383279, 1e+1000, true]`
602
603 var value any
604 err := json.Unmarshal([]byte(input), &value,
605 // Intercept every attempt to unmarshal into the any type.
606 json.WithUnmarshalers(
607 json.UnmarshalFromFunc(func(dec *jsontext.Decoder, val *any) error {
608 // If the next value to be decoded is a JSON number,
609 // then provide a concrete Go type to unmarshal into.
610 if dec.PeekKind() == '0' {
611 *val = jsontext.Value(nil)
612 }
613 // Return SkipFunc to fallback on default unmarshal behavior.
614 return json.SkipFunc
615 }),
616 ))
617 if err != nil {
618 log.Fatal(err)
619 }
620 fmt.Println(value)
621
622 // Sanity check.
623 want := []any{false, jsontext.Value("1e-1000"), jsontext.Value("3.141592653589793238462643383279"), jsontext.Value("1e+1000"), true}
624 if !reflect.DeepEqual(value, want) {
625 log.Fatalf("value mismatch:\ngot %v\nwant %v", value, want)
626 }
627
628 // Output:
629 // [false 1e-1000 3.141592653589793238462643383279 1e+1000 true]
630 }
631
632 // When using JSON for parsing configuration files,
633 // the parsing logic often needs to report an error with a line and column
634 // indicating where in the input an error occurred.
635 func ExampleWithUnmarshalers_recordOffsets() {
636 // Hypothetical configuration file.
637 const input = `[
638 {"Source": "192.168.0.100:1234", "Destination": "192.168.0.1:80"},
639 {"Source": "192.168.0.251:4004"},
640 {"Source": "192.168.0.165:8080", "Destination": "0.0.0.0:80"}
641 ]`
642 type Tunnel struct {
643 Source netip.AddrPort
644 Destination netip.AddrPort
645
646 // ByteOffset is populated during unmarshal with the byte offset
647 // within the JSON input of the JSON object for this Go struct.
648 ByteOffset int64 `json:"-"` // metadata to be ignored for JSON serialization
649 }
650
651 var tunnels []Tunnel
652 err := json.Unmarshal([]byte(input), &tunnels,
653 // Intercept every attempt to unmarshal into the Tunnel type.
654 json.WithUnmarshalers(
655 json.UnmarshalFromFunc(func(dec *jsontext.Decoder, tunnel *Tunnel) error {
656 // Decoder.InputOffset reports the offset after the last token,
657 // but we want to record the offset before the next token.
658 //
659 // Call Decoder.PeekKind to buffer enough to reach the next token.
660 // Add the number of leading whitespace, commas, and colons
661 // to locate the start of the next token.
662 dec.PeekKind()
663 unread := dec.UnreadBuffer()
664 n := len(unread) - len(bytes.TrimLeft(unread, " \n\r\t,:"))
665 tunnel.ByteOffset = dec.InputOffset() + int64(n)
666
667 // Return SkipFunc to fallback on default unmarshal behavior.
668 return json.SkipFunc
669 }),
670 ))
671 if err != nil {
672 log.Fatal(err)
673 }
674
675 // lineColumn converts a byte offset into a one-indexed line and column.
676 // The offset must be within the bounds of the input.
677 lineColumn := func(input string, offset int) (line, column int) {
678 line = 1 + strings.Count(input[:offset], "\n")
679 column = 1 + offset - (strings.LastIndex(input[:offset], "\n") + len("\n"))
680 return line, column
681 }
682
683 // Verify that the configuration file is valid.
684 for _, tunnel := range tunnels {
685 if !tunnel.Source.IsValid() || !tunnel.Destination.IsValid() {
686 line, column := lineColumn(input, int(tunnel.ByteOffset))
687 fmt.Printf("%d:%d: source and destination must both be specified", line, column)
688 }
689 }
690
691 // Output:
692 // 3:3: source and destination must both be specified
693 }