jsonpath.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. // Marshal to JSON for consistent string representation
  23. jsonBytes, err := json.Marshal(value)
  24. if err != nil {
  25. return false, fmt.Errorf("failed to marshal extracted value: %w", err)
  26. }
  27. valueStr := string(jsonBytes)
  28. return valueStr == expectedValue, nil
  29. }
  30. func (m *JSONMatcher) ExtractValue(pathExpr string) (string, error) {
  31. value, err := jsonpath.Get(pathExpr, m.payload)
  32. if err != nil {
  33. return "", err
  34. }
  35. // Marshal to JSON for consistent string representation
  36. jsonBytes, err := json.Marshal(value)
  37. if err != nil {
  38. return "", fmt.Errorf("failed to marshal extracted value: %w", err)
  39. }
  40. return string(jsonBytes), nil
  41. }
  42. func (m *JSONMatcher) GetPayload() interface{} {
  43. return m.payload
  44. }