github.com/Jeffail/benthos/v3@v3.65.0/public/service/config_output.go (about) 1 package service 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/Jeffail/benthos/v3/internal/docs" 8 "github.com/Jeffail/benthos/v3/lib/output" 9 "gopkg.in/yaml.v3" 10 ) 11 12 // NewOutputField defines a new output field, it is then possible to extract an 13 // OwnedOutput from the resulting parsed config with the method FieldOutput. 14 func NewOutputField(name string) *ConfigField { 15 return &ConfigField{ 16 field: docs.FieldCommon(name, "").HasType(docs.FieldTypeOutput), 17 } 18 } 19 20 // FieldOutput accesses a field from a parsed config that was defined with 21 // NewOutputField and returns an OwnedOutput, or an error if the configuration 22 // was invalid. 23 func (p *ParsedConfig) FieldOutput(path ...string) (*OwnedOutput, error) { 24 field, exists := p.field(path...) 25 if !exists { 26 return nil, fmt.Errorf("field '%v' was not found in the config", strings.Join(path, ".")) 27 } 28 29 pNode, ok := field.(*yaml.Node) 30 if !ok { 31 return nil, fmt.Errorf("unexpected value, expected object, got %T", field) 32 } 33 34 var conf output.Config 35 if err := pNode.Decode(&conf); err != nil { 36 return nil, err 37 } 38 39 iproc, err := p.mgr.NewOutput(conf) 40 if err != nil { 41 return nil, err 42 } 43 return newOwnedOutput(iproc) 44 } 45 46 // NewOutputListField defines a new output list field, it is then possible 47 // to extract a list of OwnedOutput from the resulting parsed config with the 48 // method FieldOutputList. 49 func NewOutputListField(name string) *ConfigField { 50 return &ConfigField{ 51 field: docs.FieldCommon(name, "").Array().HasType(docs.FieldTypeOutput), 52 } 53 } 54 55 // FieldOutputList accesses a field from a parsed config that was defined 56 // with NewOutputListField and returns a slice of OwnedOutput, or an error 57 // if the configuration was invalid. 58 func (p *ParsedConfig) FieldOutputList(path ...string) ([]*OwnedOutput, error) { 59 field, exists := p.field(path...) 60 if !exists { 61 return nil, fmt.Errorf("field '%v' was not found in the config", strings.Join(path, ".")) 62 } 63 64 fieldArray, ok := field.([]interface{}) 65 if !ok { 66 return nil, fmt.Errorf("unexpected value, expected array, got %T", field) 67 } 68 69 var configs []output.Config 70 for i, iConf := range fieldArray { 71 node, ok := iConf.(*yaml.Node) 72 if !ok { 73 return nil, fmt.Errorf("value %v returned unexpected value, expected object, got %T", i, iConf) 74 } 75 76 var conf output.Config 77 if err := node.Decode(&conf); err != nil { 78 return nil, fmt.Errorf("value %v: %w", i, err) 79 } 80 configs = append(configs, conf) 81 } 82 83 ins := make([]*OwnedOutput, len(configs)) 84 for i, c := range configs { 85 iproc, err := p.mgr.NewOutput(c) 86 if err != nil { 87 return nil, fmt.Errorf("output %v: %w", i, err) 88 } 89 if ins[i], err = newOwnedOutput(iproc); err != nil { 90 return nil, fmt.Errorf("output %v: %w", i, err) 91 } 92 } 93 94 return ins, nil 95 }