Resilient Http Request in Go
Resilience mechanism in distributed system reduce oversize request available for users.
in this part, we can make resilient using the circuit breaker pattern using a hystrix-golang
library.
breakers.go
package breakers
import (
"github.com/afex/hystrix-go/hystrix"
)
const (
FetchJson = "fetch.json"
)
func ConfigCircuitBreakers() {
breakers := make(map[string]hystrix.CommandConfig)
breakers[FetchJson] = hystrix.CommandConfig{
Timeout: 1000,
MaxConcurrentRequests: 100,
ErrorPercentThreshold: 25,
}
hystrix.Configure(breakers)
}
main.go
package main
import (
"github.com/afex/hystrix-go/hystrix"
"github.com/faizalpribadi/learn/breakers"
"io/ioutil"
"log"
"net/http"
)
func main() {
breakers.ConfigCircuitBreakers()
result := make(chan interface{}, 1)
errChan := hystrix.Go("fetch.json", func() error{
resp, err := http.Get("https://jsonplaceholder.typicode.com/todos")
if err != nil {
return err
}
value, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
result <- string(value)
return nil
}, nil)
select {
case output := <-result:
// Do some logic at here
// or run ur background job processing such as (amazon sqs, or kafka)
log.Println(output)
case errResp := <-errChan:
log.Println(errResp)
}
}