github.com/yandex/pandora@v0.5.32/components/providers/scenario/http/postprocessor/var_jsonpath.go (about)

     1  package postprocessor
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  
     9  	"github.com/PaesslerAG/jsonpath"
    10  	multierr "github.com/hashicorp/go-multierror"
    11  )
    12  
    13  type VarJsonpathPostprocessor struct {
    14  	Mapping map[string]string
    15  }
    16  
    17  func (p *VarJsonpathPostprocessor) ReturnedParams() []string {
    18  	result := make([]string, len(p.Mapping))
    19  	for k := range p.Mapping {
    20  		result = append(result, k)
    21  	}
    22  	return result
    23  }
    24  
    25  func (p *VarJsonpathPostprocessor) Process(_ *http.Response, body io.Reader) (map[string]any, error) {
    26  	if len(p.Mapping) == 0 {
    27  		return nil, nil
    28  	}
    29  	var data any
    30  	decoder := json.NewDecoder(body)
    31  	err := decoder.Decode(&data)
    32  	if err != nil {
    33  		return nil, fmt.Errorf("failed to unmarshal json: %w", err)
    34  	}
    35  	result := map[string]any{}
    36  	for k, path := range p.Mapping {
    37  		val, e := jsonpath.Get(path, data)
    38  		if e != nil {
    39  			err = multierr.Append(err, fmt.Errorf("failed to get value by jsonpath %s: %w", path, e))
    40  			continue
    41  		}
    42  		result[k] = val
    43  	}
    44  	return result, err
    45  }