Created
March 11, 2024 16:10
-
-
Save berdoezt/bb50be1afad09455d9946772ca1b6966 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"io" | |
"log" | |
"net/http" | |
"time" | |
"github.com/sony/gobreaker" | |
) | |
func main() { | |
cbs := gobreaker.Settings{ | |
Name: "cl", | |
Interval: 5 * time.Second, | |
Timeout: 7 * time.Second, | |
ReadyToTrip: func(counts gobreaker.Counts) bool { | |
failureRatio := float64(counts.TotalFailures) / float64(counts.Requests) | |
result := counts.Requests >= 3 && failureRatio >= 0.6 | |
return result | |
}, | |
OnStateChange: func(_ string, from gobreaker.State, to gobreaker.State) { | |
// Handler for every state change. We'll use for debugging purpose | |
log.Println("state changed from", from.String(), "to", to.String()) | |
}, | |
} | |
cb := gobreaker.NewCircuitBreaker(cbs) | |
for { | |
time.Sleep(1 * time.Second) | |
get(cb) | |
} | |
} | |
func get(cb *gobreaker.CircuitBreaker) { | |
_, err := cb.Execute(func() (interface{}, error) { | |
response, err := http.Get("http://localhost:8082/hello") | |
if err != nil { | |
return nil, err | |
} | |
defer response.Body.Close() | |
log.Println(response.Status) | |
dataByte, err := io.ReadAll(response.Body) | |
if err != nil { | |
return nil, err | |
} | |
log.Println(string(dataByte)) | |
if response.StatusCode == http.StatusInternalServerError { | |
return nil, errors.New("internal server error") | |
} | |
return dataByte, nil | |
}) | |
if err != nil { | |
log.Println("error cb", err) | |
return | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"net/http" | |
) | |
var isSuccess bool = true | |
func main() { | |
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { | |
log.Println("receive request") | |
if isSuccess { | |
w.WriteHeader(http.StatusOK) | |
w.Write([]byte("success response")) | |
} else { | |
w.WriteHeader(http.StatusInternalServerError) | |
w.Write([]byte("fail response")) | |
} | |
}) | |
http.HandleFunc("/toggle", func(w http.ResponseWriter, r *http.Request) { | |
if isSuccess { | |
fmt.Println("success change to false") | |
isSuccess = false | |
} else { | |
fmt.Println("success change to true") | |
isSuccess = true | |
} | |
}) | |
http.ListenAndServe("localhost:8082", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment