jsonpath.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package webhooks
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/PaesslerAG/jsonpath"
  6. )
  7. type JSONMatcher struct {
  8. payload interface{}
  9. }
  10. func NewJSONMatcher(payload []byte) (*JSONMatcher, error) {
  11. var data interface{}
  12. if err := json.Unmarshal(payload, &data); err != nil {
  13. return nil, err
  14. }
  15. return &JSONMatcher{payload: data}, nil
  16. }
  17. func (m *JSONMatcher) MatchPath(pathExpr string, expectedValue string) (bool, error) {
  18. value, err := jsonpath.Get(pathExpr, m.payload)
  19. if err != nil {
  20. return false, err
  21. }
  22. // For string values, compare directly without marshaling
  23. if strValue, ok := value.(string); ok {
  24. return strValue == expectedValue, nil
  25. }
  26. // For non-string values, marshal to JSON for consistent string representation
  27. jsonBytes, err := json.Marshal(value)
  28. if err != nil {
  29. return false, fmt.Errorf("failed to marshal extracted value: %w", err)
  30. }
  31. valueStr := string(jsonBytes)
  32. return valueStr == expectedValue, nil
  33. }
  34. func (m *JSONMatcher) ExtractValue(pathExpr string) (string, error) {
  35. value, err := jsonpath.Get(pathExpr, m.payload)
  36. if err != nil {
  37. return "", err
  38. }
  39. // Marshal to JSON for consistent string representation
  40. jsonBytes, err := json.Marshal(value)
  41. if err != nil {
  42. return "", fmt.Errorf("failed to marshal extracted value: %w", err)
  43. }
  44. return string(jsonBytes), nil
  45. }
  46. func (m *JSONMatcher) GetPayload() interface{} {
  47. return m.payload
  48. }