github.com/Jeffail/benthos/v3@v3.65.0/public/service/example_output_plugin_test.go (about) 1 package service_test 2 3 import ( 4 "context" 5 "fmt" 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 BlueOutput struct{} 14 15 func (b *BlueOutput) Connect(ctx context.Context) error { 16 return nil 17 } 18 19 func (b *BlueOutput) Write(ctx context.Context, msg *service.Message) error { 20 content, err := msg.AsBytes() 21 if err != nil { 22 return err 23 } 24 fmt.Printf("\033[01;34m%s\033[m\n", content) 25 return nil 26 } 27 28 func (b *BlueOutput) Close(ctx context.Context) error { 29 return nil 30 } 31 32 // This example demonstrates how to create an output plugin. This example is for 33 // an implementation that does not require any configuration parameters, and 34 // therefore doesn't defined any within the configuration specification. 35 func Example_outputPlugin() { 36 // Register our new output, which doesn't require a config schema. 37 err := service.RegisterOutput( 38 "blue_stdout", service.NewConfigSpec(), 39 func(conf *service.ParsedConfig, mgr *service.Resources) (out service.Output, maxInFlight int, err error) { 40 return &BlueOutput{}, 1, nil 41 }) 42 if err != nil { 43 panic(err) 44 } 45 46 // Use the stream builder API to create a Benthos stream that uses our new 47 // output type. 48 builder := service.NewStreamBuilder() 49 50 // Set the full Benthos configuration of the stream. 51 err = builder.SetYAML(` 52 input: 53 generate: 54 count: 1 55 interval: 1ms 56 mapping: 'root = "hello world"' 57 58 output: 59 blue_stdout: {} 60 `) 61 if err != nil { 62 panic(err) 63 } 64 65 // Build a stream with our configured components. 66 stream, err := builder.Build() 67 if err != nil { 68 panic(err) 69 } 70 71 // And run it, blocking until it gracefully terminates once the generate 72 // input has generated a message and it has flushed through the stream. 73 if err = stream.Run(context.Background()); err != nil { 74 panic(err) 75 } 76 77 // Output: [01;34mhello world[m 78 }