123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112 |
- package main
- import (
- "fmt"
- "io"
- "log"
- "net/http"
- "os"
- "strings"
- "time"
- h "github.com/afex/hystrix-go/hystrix"
- y "gopkg.in/yaml.v3"
- )
- var cmds = map[string]h.CommandConfig{
- "defaults": {
- Timeout: h.DefaultTimeout,
- MaxConcurrentRequests: h.DefaultMaxConcurrent,
- RequestVolumeThreshold: h.DefaultVolumeThreshold,
- SleepWindow: h.DefaultSleepWindow,
- ErrorPercentThreshold: h.DefaultErrorPercentThreshold,
- },
- "robots": {
- Timeout: 100,
- MaxConcurrentRequests: 1,
- RequestVolumeThreshold: 1,
- SleepWindow: 3000,
- ErrorPercentThreshold: 1,
- },
- }
- func robots() error {
- res, err := http.Get("https://osinet.fr/robots.txt")
- if err != nil {
- return err
- }
- if res.StatusCode >= http.StatusBadRequest {
- return fmt.Errorf("HTTP Error response: %s", res.Status)
- }
- b, err := io.ReadAll(res.Body)
- if err != nil {
- return err
- }
- fmt.Printf("%s\n", strings.Replace(string(b[0:20]), "\n", "\t", -1))
- return nil
- }
- func robotsFB(e error) error {
- ce, ok := e.(h.CircuitError)
- if !ok {
- return fmt.Errorf("unexpected error: %w", e)
- }
- switch ce.Message {
- case "circuit open":
- fmt.Println("FB Short-circuit")
- case "timeout":
- fmt.Println("FB Timeout response")
- default:
- log.Println("FB", e.Error())
- }
- return nil
- }
- func showCircuitSettings() {
- e := y.NewEncoder(os.Stdout)
- defer e.Close()
- e.SetIndent(2)
- fmt.Println(e.Encode(h.GetCircuitSettings()))
- }
- func showCircuit(name string) {
- r, created, err := h.GetCircuit(name)
- fmt.Printf("Name: %s, Created it: %t, error: %v\n", r.Name, created, err)
- if err == nil {
- fmt.Printf("IsOpen: %t, AllowRequest: %t", r.IsOpen(), r.AllowRequest())
- }
- }
- func streamStats() {
- sh := h.NewStreamHandler()
- sh.Start()
- http.Handle("/", sh)
- err := http.ListenAndServe(":4000", nil)
- fmt.Printf("L&S: %#v\n", err)
- sh.Stop()
- }
- func main() {
- h.SetLogger(log.Default())
- h.Configure(cmds)
- // showCircuit("robots")
- // show(h.GetCircuitSettings())
- go streamStats()
- for i := 0; i < 30; i++ {
- t0 := time.Now()
- err := h.Do("robots", robots, robotsFB)
- d := time.Since(t0)
- if err != nil {
- fmt.Printf("%2d in %v Error: %v\n", i, d, err)
- } else {
- fmt.Printf("%2d in %v OK\n", i, d)
- }
- time.Sleep(1000 * time.Millisecond)
- // if i%10 == 0 {
- // h.Flush()
- // }
- }
- }
|