Skip to main content
Version: v0.2.2

HTTP client

The restclient package decodes JSON responses into success and error types and integrates calls with OpenTelemetry.

Create a client

client := restclient.NewRestClient(&restclient.RestClientConfig{
Name: "users-api",
BaseURL: "https://users.example.com",
Timeout: 5,
})

Timeout is measured in seconds and defaults to one second. Use ProxyURL when requests must go through an HTTP proxy.

Execute a request

response := restclient.Request[User, APIError]{
Ctx: ctx,
Client: client,
HttpMethod: http.MethodGet,
Path: "/users/123",
Headers: map[string]string{
"Accept": "application/json",
},
}.Call()

if response.Error() != nil {
return nil, response.Error()
}
if response.HasError() {
return nil, fmt.Errorf("users API: %s", response.ErrorBody().Message)
}
return response.SuccessBody(), nil

ResponseData also exposes StatusCode(), Headers(), and helpers for 1xx through 5xx responses.

JSON and multipart bodies

Set Body to a struct to send JSON. For multipart requests:

response := restclient.Request[UploadResponse, APIError]{
Ctx: ctx,
Client: client,
HttpMethod: http.MethodPost,
Path: "/documents",
MultipartFields: map[string]any{
"file": restclient.MultipartFile{
FileName: "report.txt",
File: strings.NewReader("content"),
ContentType: "text/plain",
},
"category": "reports",
},
}.Call()

Circuit breaker and retries

The circuit breaker opens after five consecutive failures and tries recovery after ten seconds.

v0.2.2 behavior

Retries and RetrySleepInSeconds exist in RestClientConfig, but the v0.2.2 constructor does not apply them. Do not rely on automatic retries in this version.