Requests

The Go SDK provides a flexible Request type that abstracts HTTP calls, handles retries, context propagation, and integrates seamlessly with Go’s net/http package.

Creating a Request

Use client.NewRequest to build a request. You can set the method, URL, headers, query parameters, and body.

// Create a new GET request
req, err := client.NewRequest(context.Background(), http.MethodGet, "/v1/items", nil)
if err != nil {
    log.Fatalf("failed to create request: %v", err)
}

// Add custom headers
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Request-ID", "12345")

Adding a JSON Body

For POST/PUT requests, encode a struct as JSON using req.SetJSONBody.

type CreateItem struct {
    Name string `json:"name"`
    Qty  int    `json:"quantity"`
}

payload := CreateItem{Name: "Widget", Qty: 10}
req, _ := client.NewRequest(context.Background(), http.MethodPost, "/v1/items", nil)
if err := req.SetJSONBody(payload); err != nil {
    log.Fatalf("json marshal error: %v", err)
}
req.Header.Set("Content-Type", "application/json")

Sending the Request

Execute the request with client.Do. The response is unmarshalled into the provided destination.

type Item struct {
    ID   string `json:"id"`
    Name string `json:"name"`
    Qty  int    `json:"quantity"`
}

var result Item
resp, err := client.Do(req, &result)
if err != nil {
    // Automatic retry and backoff are handled internally
    log.Fatalf("request failed: %v", err)
}
fmt.Printf("Created item: %+v (status %d)\n", result, resp.StatusCode)

Retry & Timeout

The SDK supports configurable retries and per‑request timeouts via context.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

req, _ := client.NewRequest(ctx, http.MethodGet, "/v1/slow-endpoint", nil)
resp, err := client.Do(req, nil) // response ignored
if err != nil {
    if errors.Is(err, context.DeadlineExceeded) {
        fmt.Println("request timed out")
    } else {
        fmt.Printf("request error: %v\n", err)
    }
}

Advanced: Custom Transport

Inject a custom http.RoundTripper for tracing, metrics, or mock testing.

type loggingTransport struct {
    rt http.RoundTripper
}

func (l *loggingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
    fmt.Printf("→ %s %s\n", r.Method, r.URL)
    resp, err := l.rt.RoundTrip(r)
    if err == nil {
        fmt.Printf("← %d %s\n", resp.StatusCode, resp.Status)
    }
    return resp, err
}

// Configure client with custom transport
client := sdk.NewClient(&sdk.Config{
    BaseURL:    "https://api.example.com",
    HTTPClient: &http.Client{Transport: &loggingTransport{rt: http.DefaultTransport}},
})