github.com/Jeffail/benthos/v3@v3.65.0/public/service/example_rate_limit_plugin_test.go (about) 1 package service_test 2 3 import ( 4 "context" 5 "fmt" 6 "math/rand" 7 "time" 8 9 "github.com/Jeffail/benthos/v3/public/service" 10 11 // Import all standard Benthos components 12 _ "github.com/Jeffail/benthos/v3/public/components/all" 13 ) 14 15 type RandomRateLimit struct { 16 max time.Duration 17 } 18 19 func (r *RandomRateLimit) Access(context.Context) (time.Duration, error) { 20 return time.Duration(rand.Int() % int(r.max)), nil 21 } 22 23 func (r *RandomRateLimit) Close(ctx context.Context) error { 24 return nil 25 } 26 27 // This example demonstrates how to create a rate limit plugin, which is 28 // configured by providing a struct containing the fields to be parsed from 29 // within the Benthos configuration. 30 func Example_rateLimitPlugin() { 31 configSpec := service.NewConfigSpec(). 32 Summary("A rate limit that's pretty much just random."). 33 Description("I guess this isn't really that useful, sorry."). 34 Field(service.NewStringField("maximum_duration").Default("1s")) 35 36 constructor := func(conf *service.ParsedConfig, mgr *service.Resources) (service.RateLimit, error) { 37 maxDurStr, err := conf.FieldString("maximum_duration") 38 if err != nil { 39 return nil, err 40 } 41 maxDuration, err := time.ParseDuration(maxDurStr) 42 if err != nil { 43 return nil, fmt.Errorf("invalid max duration: %w", err) 44 } 45 return &RandomRateLimit{maxDuration}, nil 46 } 47 48 err := service.RegisterRateLimit("random", configSpec, constructor) 49 if err != nil { 50 panic(err) 51 } 52 53 // And then execute Benthos with: 54 // service.RunCLI(context.Background()) 55 }