Я реализовал следующий код для повторной отправки http-запросов в Go.
Во второй попытке повторной попытки я всегда получаю тело запроса как нулевое.Я попытался отложить req.body.close (), но он не работает.Может кто-нибудь, пожалуйста, помогите мне в этом вопросе?
func httpRetry(req *http.Request, timeOut time.Duration, retryAttempts int, retryDelay time.Duration) (*http.Response, error) {
attempts := 0
for {
attempts++
fmt.Println("Attempt - ", attempts)
statusCode := 0
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
var netClient = &http.Client{
Timeout: time.Second * timeOut,
Transport: tr,
}
fmt.Println("ret 88888 ", req)
response, err := netClient.Do(req)
//defer req.Body.Close()
fmt.Println(response, " dd", err)
if response != nil {
fmt.Println(response.StatusCode)
statusCode = response.StatusCode
}
if err != nil {
fmt.Println(err)
//return response, err
}
if err == nil && statusCode == http.StatusOK {
return response, nil
}
if err == nil && response != nil {
defer req.Body.Close()
}
retry := retryDecision(statusCode, attempts, retryAttempts)
if !retry {
return response, err
}
fmt.Println("Retry Attempt number", attempts)
time.Sleep(retryDelay * time.Second)
fmt.Println("After Delay")
}
}
func retryDecision(responseStatusCode int, attempts int, retryAttempts int) bool {
retry := false
fmt.Println("Retry Decision 0 ", responseStatusCode, attempts, retryAttempts)
errorCodeForRetry :=
[]int{http.StatusInternalServerError, http.StatusUnauthorized, http.StatusNotImplemented, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout}
for _, code := range errorCodeForRetry {
if code == responseStatusCode && attempts <= retryAttempts {
retry = true
}
}
fmt.Println("Retry Decision ", retry)
return retry
}
Ниже приведена подробная информация об ошибке
Attempt - 1
ret 88888 &{POST https://localhost:8080/logs/ HTTP/1.1 1 1 map[] {{"converstnId":"","boId":"","msgId":"","serviceName":"","headers":"","properties":"","message":"","body":"aa","exceptionMessage":"","logType":"","exceptionStackTrace":""}}
0x5ec890 170 [] false map [] map [] map []
}
Attempt - 2
ret 88888 &{POST https://localhost:8080/logs/ HTTP/1.1 1 1 map[] {} 0x5ec890 170 [] false map[] map[] <nil> map[]
}