Skip to content

Commit

Permalink
Use json.NewDecoder instead of trying to read JSON data
Browse files Browse the repository at this point in the history
Also correct some error handling aronud JSON parsing.
  • Loading branch information
peanball committed Apr 14, 2023
1 parent fb03161 commit 440a797
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 14 deletions.
21 changes: 8 additions & 13 deletions src/pcap/bosh.go
Original file line number Diff line number Diff line change
Expand Up @@ -291,16 +291,12 @@ func (br *BoshResolver) info() (*BoshInfo, error) {
return nil, fmt.Errorf("received non-OK response from Bosh Director: %s", response.Status)
}

var apiResponse *BoshInfo
data, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("could not read bosh-director API response: %w", err)
}
err = json.Unmarshal(data, &apiResponse)
var apiResponse BoshInfo
err = json.NewDecoder(response.Body).Decode(&apiResponse)
if err != nil {
return nil, fmt.Errorf("could not parse bosh-director API response: %w", err)
}
return apiResponse, nil
return &apiResponse, nil
}

// Healthy returns true if the resolver can retrieve /info to the BOSH director.
Expand Down Expand Up @@ -349,18 +345,17 @@ func (br *BoshResolver) getInstances(deployment string, authToken string) ([]Bos

defer func() { _ = res.Body.Close() }()

data, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

if res.StatusCode != http.StatusOK {
data, dataReadErr := io.ReadAll(res.Body)
if dataReadErr != nil {
return nil, fmt.Errorf("failed reading data of non-OK response, status %d: %w", res.StatusCode, dataReadErr)
}
return nil, fmt.Errorf("expected status code %d but got status code %d: %s", http.StatusOK, res.StatusCode, string(data))
}

var response []BoshInstance

err = json.Unmarshal(data, &response)
err = json.NewDecoder(res.Body).Decode(&response)
if err != nil {
return nil, err
}
Expand Down
2 changes: 1 addition & 1 deletion src/pcap/cmd/pcap-api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func registerBoshResolvers(configs []pcap.BoshResolverConfig, log *zap.Logger, a
for _, env := range configs {
resolver, err := pcap.NewBoshResolver(env)
if err != nil {
log.With(zap.String(pcap.LogKeyResolver, env.EnvironmentAlias)).Error("Failed to setup BoshResolver", zap.Error(err))
log.Error("Failed to setup BoshResolver", zap.String(pcap.LogKeyResolver, env.EnvironmentAlias), zap.Error(err))
return err
}
api.RegisterResolver(resolver)
Expand Down

0 comments on commit 440a797

Please sign in to comment.