github.com/Jeffail/benthos/v3@v3.65.0/public/service/example_input_plugin_test.go (about) 1 package service_test 2 3 import ( 4 "context" 5 "math/rand" 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 GibberishInput struct { 14 length int 15 } 16 17 func (g *GibberishInput) Connect(ctx context.Context) error { 18 return nil 19 } 20 21 func (g *GibberishInput) Read(ctx context.Context) (*service.Message, service.AckFunc, error) { 22 b := make([]byte, g.length) 23 for k := range b { 24 b[k] = byte((rand.Int() % 94) + 32) 25 } 26 return service.NewMessage(b), func(ctx context.Context, err error) error { 27 // A nack (when err is non-nil) is handled automatically when we 28 // construct using service.AutoRetryNacks, so we don't need to handle 29 // nacks here. 30 return nil 31 }, nil 32 } 33 34 func (g *GibberishInput) Close(ctx context.Context) error { 35 return nil 36 } 37 38 // This example demonstrates how to create an input plugin, which is configured 39 // by providing a struct containing the fields to be parsed from within the 40 // Benthos configuration. 41 func Example_inputPlugin() { 42 configSpec := service.NewConfigSpec(). 43 Summary("Creates a load of gibberish, putting us all out of work."). 44 Field(service.NewIntField("length").Default(100)) 45 46 constructor := func(conf *service.ParsedConfig, mgr *service.Resources) (service.Input, error) { 47 length, err := conf.FieldInt("length") 48 if err != nil { 49 return nil, err 50 } 51 return service.AutoRetryNacks(&GibberishInput{length}), nil 52 } 53 54 err := service.RegisterInput("gibberish", configSpec, constructor) 55 if err != nil { 56 panic(err) 57 } 58 59 // And then execute Benthos with: 60 // service.RunCLI(context.Background()) 61 }