Mode:
Duration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main
import (
"context"
"fmt"
"time"
)
func callService(ctx context.Context) error {
select {
case <-time.After(500 * time.Millisecond):
return fmt.Errorf("service unavailable")
case <-ctx.Done():
return ctx.Err()
}
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
for retry := 1; retry <= 3; retry++ {
err := callService(ctx)
if err == nil {
fmt.Println("Request succeeded")
return
}
fmt.Printf("Retry %d failed: %v\n", retry, err)
}
fmt.Println("Circuit Breaker Open")
fmt.Println("Requests redirected to fallback")
}Coding works best on desktop or with an external keyboard.