Skip to content

Commit d5a656f

Browse files
committed
Example: Create a basic example to start with Toxics
Real life working example to create a new toxic. Add readme to show how to test toxics.
1 parent d2ae089 commit d5a656f

2 files changed

Lines changed: 83 additions & 0 deletions

File tree

examples/toxics/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Examples
2+
3+
Example how to start building own toxics.
4+
5+
Run custom toxiserver with DebugToxic.
6+
7+
```shell
8+
$ go run debug_toxic.go
9+
```
10+
11+
Run redis-server in separate terminal:
12+
13+
```shell
14+
$ redis-server
15+
```
16+
17+
Test toxic with:
18+
19+
```shell
20+
$ toxiproxy-cli --host "http://localhost:8484" create -l :16379 -u localhost:6379 redis
21+
$ toxiproxy-cli --host "http://localhost:8484" t add --type debug redis
22+
$ redis-cli -p 16379 "keys" "*"
23+
```
24+
25+
Custom Toxiproxy should print bytes in hex format.

examples/toxics/debug_toxic.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package main
2+
3+
import (
4+
"os"
5+
"log"
6+
"fmt"
7+
8+
"github.com/prometheus/client_golang/prometheus"
9+
"github.com/rs/zerolog"
10+
11+
"github.com/Shopify/toxiproxy/v2"
12+
"github.com/Shopify/toxiproxy/v2/toxics"
13+
)
14+
15+
// DebugToxic prints bytes processed through pipe.
16+
type DebugToxic struct{}
17+
18+
func (t *DebugToxic) PrintHex(data []byte) {
19+
for i := 0; i < len(data); {
20+
for j := 0; j < 4; j +=1 {
21+
x := i + 8
22+
if x >= len(data) {
23+
x = len(data) - 1
24+
fmt.Printf("% x\n", data[i:x])
25+
return
26+
}
27+
fmt.Printf("% x\t\t", data[i:x])
28+
i = x
29+
}
30+
fmt.Println()
31+
}
32+
}
33+
34+
func (t *DebugToxic) Pipe(stub *toxics.ToxicStub) {
35+
for {
36+
select {
37+
case <-stub.Interrupt:
38+
return
39+
case c := <-stub.Input:
40+
if c == nil {
41+
stub.Close()
42+
return
43+
}
44+
log.Printf("-- [DebugToxic] Processed %d bytes\n", len(c.Data))
45+
t.PrintHex(c.Data)
46+
stub.Output <- c
47+
}
48+
}
49+
}
50+
51+
func main() {
52+
toxics.Register("debug", new(DebugToxic))
53+
54+
logger := zerolog.New(os.Stderr).With().Caller().Timestamp().Logger()
55+
metrics := toxiproxy.NewMetricsContainer(prometheus.NewRegistry())
56+
server := toxiproxy.NewServer(metrics, logger)
57+
server.Listen("0.0.0.0:8484")
58+
}

0 commit comments

Comments
 (0)