add a context for params

This commit is contained in:
Edward 2020-05-22 18:14:19 +08:00
parent 48a219b987
commit 7b0110f123
3 changed files with 21 additions and 8 deletions

View File

@ -1,6 +1,9 @@
package circuit
import "time"
import (
"context"
"time"
)
//BreakConditionWatcher check state
type BreakConditionWatcher func(cnter counters) bool
@ -19,6 +22,7 @@ type Options struct {
MaxRequests uint32
WhenToBreak BreakConditionWatcher //是否应该断开电路(打开电路开关)
OnStateChanged StateChangedEventHandler
Ctx context.Context
}
//Name of breaker

View File

@ -9,10 +9,12 @@
package circuit
import (
"errors"
"context"
"context
"erros"
"fmt"
"sync"
"time"
time"
)
////////////////////////////////
@ -77,19 +79,26 @@ func NewRequestBreaker(opts ...Option) *RequestBreaker {
// Do returns an error instantly if the RequestBreaker rejects the request.
// Otherwise, Execute returns the result of the request.
// If a panic occurs in the request, the RequestBreaker handles it as an error and causes the same panic again.
func (rb *RequestBreaker) Do(work func() (interface{}, error)) (interface{}, error) {
func (rb *RequestBreaker) Do(work func(ctx context.Context) (interface{}, error)) (interface{}, error) {
//before
fmt.Println("before do : request:", rb.cnter.Total())
//handle status
rb.mutex.Lock()
//handle status of Open to HalfOpen
if rb.state == StateOpen && rb.options.Expiry.Before(time.Now()) {
}
rb.mutex.Unlock()
//do work from requested user
result, err := work()
result, err := work(rb.options.Ctx)
if err != nil {
rb.cnter.Count(FailureState)
} else {
rb.cnter.Count(SuccessState)
}
fmt.Println("after do : request:", rb.cnter.Total())

View File

@ -31,7 +31,7 @@ var whenConditionOccurred = func(cnter counters) bool {
func TestObjectBreaker(t *testing.T) {
jobToDo := func() (interface{}, error) {
jobToDo := func(ctx context.Context) (interface{}, error) {
resp, err := http.Get("https://bing.com/robots.txt")
if err != nil {
return nil, err