github.com/prebid/prebid-server/v2@v2.18.0/adservertargeting/utils.go (about)

     1  package adservertargeting
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/buger/jsonparser"
     7  	"github.com/pkg/errors"
     8  	"github.com/prebid/prebid-server/v2/errortypes"
     9  	"github.com/prebid/prebid-server/v2/openrtb_ext"
    10  )
    11  
    12  func splitAndGet(path string, data []byte, delimiter string) (string, error) {
    13  	keySplit := strings.Split(path, delimiter)
    14  
    15  	value, err := typedLookup(data, path, keySplit...)
    16  	if err != nil {
    17  		return "", err
    18  	}
    19  
    20  	return string(value), nil
    21  }
    22  
    23  func createWarning(message string) openrtb_ext.ExtBidderMessage {
    24  	return openrtb_ext.ExtBidderMessage{
    25  		Code:    errortypes.AdServerTargetingWarningCode,
    26  		Message: message,
    27  	}
    28  }
    29  
    30  func verifyPrefixAndTrim(path, prefix string) (string, bool) {
    31  	ampDataSplit := strings.Split(path, prefix)
    32  	if len(ampDataSplit) == 2 && ampDataSplit[0] == "" {
    33  		return ampDataSplit[1], true
    34  	}
    35  	return "", false
    36  }
    37  
    38  func typedLookup(data []byte, path string, keys ...string) ([]byte, error) {
    39  	value, dataType, _, err := jsonparser.Get(data, keys...)
    40  	if err != nil && err != jsonparser.KeyPathNotFoundError {
    41  		return nil, err
    42  	} else if err != nil && err == jsonparser.KeyPathNotFoundError {
    43  		return nil, errors.Errorf("value not found for path: %s", path)
    44  	}
    45  	if verifyType(dataType) {
    46  		return value, nil
    47  	}
    48  	return nil, errors.Errorf("incorrect value type for path: %s, value can only be string or number", path)
    49  }
    50  
    51  func verifyType(dataType jsonparser.ValueType) bool {
    52  	typeAllowed := false
    53  	for _, allowedType := range allowedTypes {
    54  		if dataType == allowedType {
    55  			return true
    56  		}
    57  	}
    58  	return typeAllowed
    59  }