scope.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// Scope is the identifying values of the instrumentation scope.
15type Scope struct {
16	Name         string `json:"name,omitempty"`
17	Version      string `json:"version,omitempty"`
18	Attrs        []Attr `json:"attributes,omitempty"`
19	DroppedAttrs uint32 `json:"droppedAttributesCount,omitempty"`
20}
21
22// UnmarshalJSON decodes the OTLP formatted JSON contained in data into r.
23func (s *Scope) UnmarshalJSON(data []byte) error {
24	decoder := json.NewDecoder(bytes.NewReader(data))
25
26	t, err := decoder.Token()
27	if err != nil {
28		return err
29	}
30	if t != json.Delim('{') {
31		return errors.New("invalid Scope type")
32	}
33
34	for decoder.More() {
35		keyIface, err := decoder.Token()
36		if err != nil {
37			if errors.Is(err, io.EOF) {
38				// Empty.
39				return nil
40			}
41			return err
42		}
43
44		key, ok := keyIface.(string)
45		if !ok {
46			return fmt.Errorf("invalid Scope field: %#v", keyIface)
47		}
48
49		switch key {
50		case "name":
51			err = decoder.Decode(&s.Name)
52		case "version":
53			err = decoder.Decode(&s.Version)
54		case "attributes":
55			err = decoder.Decode(&s.Attrs)
56		case "droppedAttributesCount", "dropped_attributes_count":
57			err = decoder.Decode(&s.DroppedAttrs)
58		default:
59			// Skip unknown.
60		}
61
62		if err != nil {
63			return err
64		}
65	}
66	return nil
67}