github.com/lulzWill/go-agent@v2.1.2+incompatible/internal/cat/synthetics.go (about)

     1  package cat
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"fmt"
     7  )
     8  
     9  // SyntheticsHeader represents a decoded Synthetics header.
    10  type SyntheticsHeader struct {
    11  	Version    int
    12  	AccountID  int
    13  	ResourceID string
    14  	JobID      string
    15  	MonitorID  string
    16  }
    17  
    18  var (
    19  	errInvalidSyntheticsJSON       = errors.New("invalid synthetics JSON")
    20  	errInvalidSyntheticsVersion    = errors.New("version is not a float64")
    21  	errInvalidSyntheticsAccountID  = errors.New("account ID is not a float64")
    22  	errInvalidSyntheticsResourceID = errors.New("synthetics resource ID is not a string")
    23  	errInvalidSyntheticsJobID      = errors.New("synthetics job ID is not a string")
    24  	errInvalidSyntheticsMonitorID  = errors.New("synthetics monitor ID is not a string")
    25  )
    26  
    27  type errUnexpectedSyntheticsVersion int
    28  
    29  func (e errUnexpectedSyntheticsVersion) Error() string {
    30  	return fmt.Sprintf("unexpected synthetics header version: %d", e)
    31  }
    32  
    33  // UnmarshalJSON unmarshalls a SyntheticsHeader from raw JSON.
    34  func (s *SyntheticsHeader) UnmarshalJSON(data []byte) error {
    35  	var ok bool
    36  	var v interface{}
    37  
    38  	if err := json.Unmarshal(data, &v); err != nil {
    39  		return err
    40  	}
    41  
    42  	arr, ok := v.([]interface{})
    43  	if !ok {
    44  		return errInvalidSyntheticsJSON
    45  	}
    46  	if len(arr) != 5 {
    47  		return errUnexpectedArraySize{
    48  			label:    "unexpected number of application data elements",
    49  			expected: 5,
    50  			actual:   len(arr),
    51  		}
    52  	}
    53  
    54  	version, ok := arr[0].(float64)
    55  	if !ok {
    56  		return errInvalidSyntheticsVersion
    57  	}
    58  	s.Version = int(version)
    59  	if s.Version != 1 {
    60  		return errUnexpectedSyntheticsVersion(s.Version)
    61  	}
    62  
    63  	accountID, ok := arr[1].(float64)
    64  	if !ok {
    65  		return errInvalidSyntheticsAccountID
    66  	}
    67  	s.AccountID = int(accountID)
    68  
    69  	if s.ResourceID, ok = arr[2].(string); !ok {
    70  		return errInvalidSyntheticsResourceID
    71  	}
    72  
    73  	if s.JobID, ok = arr[3].(string); !ok {
    74  		return errInvalidSyntheticsJobID
    75  	}
    76  
    77  	if s.MonitorID, ok = arr[4].(string); !ok {
    78  		return errInvalidSyntheticsMonitorID
    79  	}
    80  
    81  	return nil
    82  }