jsonpath.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. // For string values, return directly without marshaling to avoid adding JSON quotes
  40. if strValue, ok := value.(string); ok {
  41. return strValue, nil
  42. }
  43. // For non-string values, marshal to JSON for consistent string representation
  44. jsonBytes, err := json.Marshal(value)
  45. if err != nil {
  46. return "", fmt.Errorf("failed to marshal extracted value: %w", err)
  47. }
  48. return string(jsonBytes), nil
  49. }
  50. func (m *JSONMatcher) GetPayload() interface{} {
  51. return m.payload
  52. }