resource.go

 1// Copyright The OpenTelemetry Authors
 2// SPDX-License-Identifier: Apache-2.0
 3
 4package telemetry
 5
 6import (
 7	"bytes"
 8	"encoding/json"
 9	"errors"
10	"fmt"
11	"io"
12)
13
14// Resource information.
15type Resource struct {
16	// Attrs are the set of attributes that describe the resource. Attribute
17	// keys MUST be unique (it is not allowed to have more than one attribute
18	// with the same key).
19	Attrs []Attr `json:"attributes,omitempty"`
20	// DroppedAttrs is the number of dropped attributes. If the value
21	// is 0, then no attributes were dropped.
22	DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
23}
24
25// UnmarshalJSON decodes the OTLP formatted JSON contained in data into r.
26func (r *Resource) UnmarshalJSON(data []byte) error {
27	decoder := json.NewDecoder(bytes.NewReader(data))
28
29	t, err := decoder.Token()
30	if err != nil {
31		return err
32	}
33	if t != json.Delim('{') {
34		return errors.New("invalid Resource type")
35	}
36
37	for decoder.More() {
38		keyIface, err := decoder.Token()
39		if err != nil {
40			if errors.Is(err, io.EOF) {
41				// Empty.
42				return nil
43			}
44			return err
45		}
46
47		key, ok := keyIface.(string)
48		if !ok {
49			return fmt.Errorf("invalid Resource field: %#v", keyIface)
50		}
51
52		switch key {
53		case "attributes":
54			err = decoder.Decode(&r.Attrs)
55		case "droppedAttributesCount", "dropped_attributes_count":
56			err = decoder.Decode(&r.DroppedAttrs)
57		default:
58			// Skip unknown.
59		}
60
61		if err != nil {
62			return err
63		}
64	}
65	return nil
66}