1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
package httprc_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"time"
"github.com/lestrrat-go/httprc/v3"
)
// Example_err_not_ready_checking_underlying_error demonstrates how to check
// the underlying error wrapped by ErrNotReady
func Example_err_not_ready_checking_underlying_error() {
ctx := context.Background()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
time.Sleep(2 * time.Second)
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}))
defer srv.Close()
cl := httprc.NewClient()
ctrl, err := cl.Start(ctx)
if err != nil {
fmt.Println("Failed to start client:", err)
return
}
defer ctrl.Shutdown(time.Second)
resource, err := httprc.NewResource[map[string]string](
srv.URL,
httprc.JSONTransformer[map[string]string](),
)
if err != nil {
fmt.Println("Failed to create resource:", err)
return
}
// Add with timeout
addCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()
err = ctrl.Add(addCtx, resource)
if err != nil {
if errors.Is(err, httprc.ErrNotReady()) {
// Resource registered, check why it's not ready
// errors.Is() automatically unwraps the error chain
if errors.Is(err, context.DeadlineExceeded) {
fmt.Println("Resource registered but timed out waiting for data")
fmt.Println("Will continue fetching in background")
} else {
fmt.Printf("Resource registered but not ready: %v\n", err)
}
return
}
// Registration failed
fmt.Println("Registration failed:", err)
return
}
fmt.Println("Resource ready")
// OUTPUT:
// Resource registered but timed out waiting for data
// Will continue fetching in background
}
|