git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/retry/examples/http_get_test.go (about)

     1  package retry_test
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"testing"
     9  
    10  	"git.sr.ht/~pingoo/stdx/retry"
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestGet(t *testing.T) {
    15  	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    16  		fmt.Fprintln(w, "hello")
    17  	}))
    18  	defer ts.Close()
    19  
    20  	var body []byte
    21  
    22  	err := retry.Do(
    23  		func() error {
    24  			resp, err := http.Get(ts.URL)
    25  
    26  			if err == nil {
    27  				defer func() {
    28  					if err := resp.Body.Close(); err != nil {
    29  						panic(err)
    30  					}
    31  				}()
    32  				body, err = ioutil.ReadAll(resp.Body)
    33  			}
    34  
    35  			return err
    36  		},
    37  	)
    38  
    39  	assert.NoError(t, err)
    40  	assert.NotEmpty(t, body)
    41  }