Last active
May 25, 2024 15:36
-
-
Save SirPhemmiey/1f8b7f4db50e443f21be6cadf971dc86 to your computer and use it in GitHub Desktop.
Implementing a basic circuit breaker pattern in go
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" | |
"net/http" | |
"time" | |
"github.com/sony/gobreaker" | |
) | |
func callExternalAPI() (int, error) { | |
resp, err := http.Get("https://example.com/api") | |
if err != nil { | |
return 0, err | |
} | |
defer resp.Body.Close() | |
return resp.StatusCode, nil | |
} | |
func main() { | |
settings := gobreaker.Settings{ | |
Name: "API Circuit Breaker", | |
MaxRequests: 5, | |
Interval: 60 * time.Second, | |
Timeout: 30 * time.Second, | |
ReadyToTrip: func(counts gobreaker.Counts) bool { | |
return counts.ConsecutiveFailures > 3 | |
}, | |
OnStateChange: func(name string, from gobreaker.State, to gobreaker.State) { | |
fmt.Printf("Circuit Breaker %s changed from %s to %s\n", name, from, to) | |
}, | |
} | |
cb := gobreaker.NewCircuitBreaker(settings) | |
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) { | |
_, err := cb.Execute(func() (interface{}, error) { | |
return callExternalAPI() | |
}) | |
if err != nil { | |
http.Error(w, "Service Unavailable", http.StatusServiceUnavailable) | |
return | |
} | |
w.Write([]byte("Request succeeded")) | |
}) | |
fmt.Println("Starting server on :8111...") | |
if err := http.ListenAndServe(":8111", nil); err != nil { | |
fmt.Printf("Server failed to start: %v\n", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment