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

     1  package service_test
     2  
     3  import (
     4  	"bytes"
     5  	"context"
     6  
     7  	"github.com/Jeffail/benthos/v3/public/service"
     8  
     9  	// Import all standard Benthos components
    10  	_ "github.com/Jeffail/benthos/v3/public/components/all"
    11  )
    12  
    13  type ReverseProcessor struct {
    14  	logger *service.Logger
    15  }
    16  
    17  func (r *ReverseProcessor) Process(ctx context.Context, m *service.Message) (service.MessageBatch, error) {
    18  	bytesContent, err := m.AsBytes()
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	newBytes := make([]byte, len(bytesContent))
    24  	for i, b := range bytesContent {
    25  		newBytes[len(newBytes)-i-1] = b
    26  	}
    27  
    28  	if bytes.Equal(newBytes, bytesContent) {
    29  		r.logger.Infof("Woah! This is like totally a palindrome: %s", bytesContent)
    30  	}
    31  
    32  	m.SetBytes(newBytes)
    33  	return []*service.Message{m}, nil
    34  }
    35  
    36  func (r *ReverseProcessor) Close(ctx context.Context) error {
    37  	return nil
    38  }
    39  
    40  // This example demonstrates how to create a processor plugin. This example is
    41  // for an implementation that does not require any configuration parameters, and
    42  // therefore doesn't defined any within the configuration specification.
    43  func Example_processorPlugin() {
    44  	// Register our new processor, which doesn't require a config schema.
    45  	err := service.RegisterProcessor(
    46  		"reverse", service.NewConfigSpec(),
    47  		func(conf *service.ParsedConfig, mgr *service.Resources) (service.Processor, error) {
    48  			return &ReverseProcessor{logger: mgr.Logger()}, nil
    49  		})
    50  	if err != nil {
    51  		panic(err)
    52  	}
    53  
    54  	// Build a Benthos stream that uses our new output type.
    55  	builder := service.NewStreamBuilder()
    56  
    57  	// Set the full Benthos configuration of the stream.
    58  	err = builder.SetYAML(`
    59  input:
    60    generate:
    61      count: 1
    62      interval: 1ms
    63      mapping: 'root = "hello world"'
    64  
    65  pipeline:
    66    processors:
    67      - reverse: {}
    68  
    69  output:
    70    stdout: {}
    71  `)
    72  	if err != nil {
    73  		panic(err)
    74  	}
    75  
    76  	// Build a stream with our configured components.
    77  	stream, err := builder.Build()
    78  	if err != nil {
    79  		panic(err)
    80  	}
    81  
    82  	// And run it, blocking until it gracefully terminates once the generate
    83  	// input has generated a message and it has flushed through the stream.
    84  	if err = stream.Run(context.Background()); err != nil {
    85  		panic(err)
    86  	}
    87  
    88  	// Output: dlrow olleh
    89  }