github.com/Jeffail/benthos/v3@v3.65.0/public/service/config_interpolated_string.go (about)

     1  package service
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/Jeffail/benthos/v3/internal/docs"
     8  )
     9  
    10  // NewInterpolatedStringField defines a new config field that describes a
    11  // dynamic string that supports Bloblang interpolation functions. It is then
    12  // possible to extract an *InterpolatedString from the resulting parsed config
    13  // with the method FieldInterpolatedString.
    14  func NewInterpolatedStringField(name string) *ConfigField {
    15  	tf := docs.FieldCommon(name, "").HasType(docs.FieldTypeString).IsInterpolated()
    16  	return &ConfigField{field: tf}
    17  }
    18  
    19  // FieldInterpolatedString accesses a field from a parsed config that was
    20  // defined with NewInterpolatedStringField and returns either an
    21  // *InterpolatedString or an error if the string was invalid.
    22  func (p *ParsedConfig) FieldInterpolatedString(path ...string) (*InterpolatedString, error) {
    23  	v, exists := p.field(path...)
    24  	if !exists {
    25  		return nil, fmt.Errorf("field '%v' was not found in the config", strings.Join(path, "."))
    26  	}
    27  
    28  	str, ok := v.(string)
    29  	if !ok {
    30  		return nil, fmt.Errorf("expected field '%v' to be a string, got %T", strings.Join(path, "."), v)
    31  	}
    32  
    33  	e, err := p.mgr.BloblEnvironment().NewField(str)
    34  	if err != nil {
    35  		return nil, fmt.Errorf("failed to parse interpolated field '%v': %v", strings.Join(path, "."), err)
    36  	}
    37  
    38  	return &InterpolatedString{expr: e}, nil
    39  }