Skip to content

Commit

Permalink
Add examples
Browse files Browse the repository at this point in the history
  • Loading branch information
deankarn committed Mar 25, 2024
1 parent 6f72ee5 commit 9e5a1b6
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
53 changes: 53 additions & 0 deletions _examples/net/http/retrier/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package main

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"time"

appext "github.com/go-playground/pkg/v5/app"
errorsext "github.com/go-playground/pkg/v5/errors"
httpext "github.com/go-playground/pkg/v5/net/http"
. "github.com/go-playground/pkg/v5/values/result"
)

// customize as desired to meet your needs including custom retryable status codes, errors etc.
var retrier = httpext.NewRetryer()

func main() {
ctx := appext.Context().Build()

type Test struct {
Date time.Time
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = httpext.JSON(w, http.StatusOK, Test{Date: time.Now().UTC()})
}))
defer server.Close()

// fetch response
fn := func(ctx context.Context) Result[*http.Request, error] {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)
if err != nil {
return Err[*http.Request, error](err)
}
return Ok[*http.Request, error](req)
}

var result Test
err := retrier.Do(ctx, fn, &result, http.StatusOK)
if err != nil {
panic(err)
}
fmt.Printf("Response: %+v\n", result)

// `Retrier` configuration is copy and so the base `Retrier` can be used and even customized for one-off requests.
// eg for this request we only want max attempt of 2 instead of default.
err = retrier.MaxAttempts(errorsext.MaxAttempts, 2).Do(ctx, fn, &result, http.StatusOK)
if err != nil {
panic(err)
}
fmt.Printf("Response: %+v\n", result)
}
3 changes: 3 additions & 0 deletions net/http/retrier.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ type DecodeAnyFn func(ctx context.Context, resp *http.Response, maxMemory bytese
type IsRetryableStatusCodeFn2 func(ctx context.Context, code int) bool

// Retryer is used to retry any fallible operation.
//
// The `Retryer` is designed to be stateless and reusable. Configuration is also copy and so a base `Retryer` can be
// used and changed for one-off requests eg. changing max attempts resulting in a new `Retrier` for that request.
type Retryer struct {
isRetryableFn errorsext.IsRetryableFn2[error]
isRetryableStatusCodeFn IsRetryableStatusCodeFn2
Expand Down

0 comments on commit 9e5a1b6

Please sign in to comment.