Last active
June 11, 2024 01:03
-
-
Save ignaciogutierrez/c215f8d53950b933cb93ef395cfe438b to your computer and use it in GitHub Desktop.
Pruebas de retry POST request in GoLang
This file contains hidden or 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 ( | |
"bytes" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"time" | |
) | |
/* | |
El proyecto https://httpbin.org sirve para hacer pruebas de request ! | |
Para simular un timbrado que demora, | |
usaremos la ruta delay con el metodo POST | |
https://httpbin.org/#/Dynamic_data/post_delay__delay_ | |
*/ | |
func tryPost(url string, body string) (int, []byte, error) { | |
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer([]byte(body))) | |
if err != nil { | |
return 0, nil, err | |
} | |
req.Header.Add("Content-Type", "application/json") | |
client := &http.Client{ | |
Timeout: time.Second * 5, | |
} | |
fmt.Printf("Voy a Esperar 5 segundos ... probando %s\n", url) | |
resp, err := client.Do(req) | |
if err != nil { | |
return 0, nil, err | |
} | |
defer resp.Body.Close() | |
respbody, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
return 0, nil, err | |
} | |
return resp.StatusCode, respbody, nil | |
} | |
func main() { | |
url := "https://httpbin.org/delay/" | |
body := `{"message": "hello Mr Server, this is me !"}` | |
codestatus := 0 | |
var respbytes []byte | |
var err error | |
for i := 6; i > 0; i-- { | |
requrl := fmt.Sprintf("%s%d", url, i) | |
codestatus, respbytes, err = tryPost(requrl, body) | |
if err == nil { | |
break | |
} | |
fmt.Printf("Falla %v\n\n", err) | |
} | |
fmt.Printf("%d %s\n", codestatus, string(respbytes)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment