Cliente HTTP
O pacote restclient converte respostas JSON em tipos de sucesso e erro e integra chamadas ao OpenTelemetry.
Criar o cliente
client := restclient.NewRestClient(&restclient.RestClientConfig{
Name: "users-api",
BaseURL: "https://users.example.com",
Timeout: 5,
})
Timeout é informado em segundos; o padrão é 1 segundo. ProxyURL pode ser usado quando a chamada precisa passar por um proxy HTTP.
Executar uma requisição
type User struct {
ID string `json:"id"`
Name string `json:"name"`
}
type APIError struct {
Message string `json:"message"`
}
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
Além dos corpos tipados, ResponseData expõe StatusCode(), Headers() e verificadores para respostas 1xx, 2xx, 3xx, 4xx e 5xx.
Enviar JSON
response := restclient.Request[User, APIError]{
Ctx: ctx,
Client: client,
HttpMethod: http.MethodPost,
Path: "/users",
Body: CreateUser{Name: "Maria"},
}.Call()
O SDK serializa Body como JSON. Quando Body é uma string, ela é enviada diretamente.
Multipart
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()
Cache
response := restclient.Request[User, APIError]{
Ctx: ctx,
Client: client,
HttpMethod: http.MethodGet,
Path: "/users/123",
Cache: cacheDB.NewCache[User]("remote-user-123", 5*time.Minute),
}.Call()
Um valor encontrado no cache é retornado com status 304.
Circuit breaker e retry
O circuit breaker abre depois de cinco falhas consecutivas e tenta recuperação após 10 segundos.
Comportamento da v0.2.2
Retries e RetrySleepInSeconds existem em RestClientConfig, mas não são aplicados pelo construtor da v0.2.2. Não dependa de retry automático nesta versão.