simplify consul client a little bit

This commit is contained in:
Umputun 2021-05-13 02:00:13 -05:00
parent 144902dd2f
commit d982796e58
2 changed files with 8 additions and 28 deletions

View File

@ -3,8 +3,6 @@ package consulcatalog
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"sort"
"strings"
@ -68,24 +66,15 @@ func (cl *consulClient) getServiceNames() ([]string, error) {
if err != nil {
return nil, fmt.Errorf("error send request to consul, %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected response status code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error read response body, %w", err)
}
err = resp.Body.Close()
if err != nil {
log.Printf("[ERROR] error close body, %v", err)
}
result := map[string][]string{}
err = json.Unmarshal(body, &result)
if err != nil {
if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, fmt.Errorf("error unmarshal consul response, %w", err)
}
@ -118,24 +107,14 @@ func (cl *consulClient) getServices(serviceName string) ([]consulService, error)
if err != nil {
return nil, fmt.Errorf("error send request to consul, %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected response status code %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error read response body, %w", err)
}
err = resp.Body.Close()
if err != nil {
log.Printf("[ERROR] error close body, %v", err)
}
var services []consulService
err = json.Unmarshal(body, &services)
if err != nil {
if err = json.NewDecoder(resp.Body).Decode(&services); err != nil {
return nil, fmt.Errorf("error unmarshal consul response, %w", err)
}

View File

@ -1,12 +1,13 @@
package consulcatalog
import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewClient(t *testing.T) {
@ -254,5 +255,5 @@ func TestClient_Get_error_get_services(t *testing.T) {
_, err := cl.Get()
require.Error(t, err)
assert.Equal(t, "error get service names, error unmarshal consul response, unexpected end of JSON input", err.Error())
assert.Equal(t, "error get service names, error unmarshal consul response, EOF", err.Error())
}