go-pattern-examples/resiliency/01_circuit_breaker/gobreaker/gobreaker_example_test.go

61 lines
943 B
Go
Raw Normal View History

package gobreaker
import (
"fmt"
"io/ioutil"
"net/http"
2020-05-08 11:45:03 +03:00
"testing"
)
2020-05-08 11:45:03 +03:00
var cb *CircuitBreaker
func TestGoBreaker(t *testing.T) {
2020-05-08 11:45:03 +03:00
initBreaker()
body, err := Get("https://bing.com/robots.txt")
if err != nil {
t.Fatal(err)
}
fmt.Println(string(body))
}
func initBreaker() {
2020-05-08 11:45:03 +03:00
var st Settings
st.Name = "HTTP GET"
2020-05-08 11:45:03 +03:00
st.ReadyToTrip = func(counts Counts) bool {
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests)
return counts.Requests >= 3 && failureRatio >= 0.6
}
2020-05-08 11:45:03 +03:00
cb = NewCircuitBreaker(st)
}
// Get wraps http.Get in CircuitBreaker.
func Get(url string) ([]byte, error) {
body, err := cb.Execute(func() (interface{}, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return body, nil
})
if err != nil {
return nil, err
}
return body.([]byte), nil
2020-05-08 11:45:03 +03:00
}