github.com/Jeffail/benthos/v3@v3.65.0/website/static/snippets/write-a-benthos-plugin/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "strconv" 6 "time" 7 8 "github.com/Jeffail/benthos/v3/lib/log" 9 "github.com/Jeffail/benthos/v3/lib/metrics" 10 "github.com/Jeffail/benthos/v3/lib/processor" 11 "github.com/Jeffail/benthos/v3/lib/service" 12 "github.com/Jeffail/benthos/v3/lib/types" 13 ) 14 15 // HowSarcastic totally detects sarcasm every time. 16 func HowSarcastic(content []byte) float64 { 17 if bytes.Contains(bytes.ToLower(content), []byte("/s")) { 18 return 100 19 } 20 return 0 21 } 22 23 // SarcasmProc applies our sarcasm detector to messages. 24 type SarcasmProc struct { 25 MetadataKey string `json:"metadata_key" yaml:"metadata_key"` 26 } 27 28 // ProcessMessage returns messages mutated with their sarcasm level. 29 func (s *SarcasmProc) ProcessMessage(msg types.Message) ([]types.Message, types.Response) { 30 newMsg := msg.Copy() 31 32 newMsg.Iter(func(i int, p types.Part) error { 33 sarcasm := HowSarcastic(p.Get()) 34 sarcasmStr := strconv.FormatFloat(sarcasm, 'f', -1, 64) 35 36 if len(s.MetadataKey) > 0 { 37 p.Metadata().Set(s.MetadataKey, sarcasmStr) 38 } else { 39 p.Set([]byte(sarcasmStr)) 40 } 41 return nil 42 }) 43 44 return []types.Message{newMsg}, nil 45 } 46 47 // CloseAsync does nothing. 48 func (s *SarcasmProc) CloseAsync() {} 49 50 // WaitForClose does nothing. 51 func (s *SarcasmProc) WaitForClose(timeout time.Duration) error { 52 return nil 53 } 54 55 func main() { 56 processor.RegisterPlugin( 57 "how_sarcastic", 58 func() interface{} { 59 s := SarcasmProc{} 60 return &s 61 }, 62 func( 63 iconf interface{}, 64 mgr types.Manager, 65 logger log.Modular, 66 stats metrics.Type, 67 ) (types.Processor, error) { 68 return iconf.(*SarcasmProc), nil 69 }, 70 ) 71 72 service.Run() 73 }