Skip to content

Commit 40e36cc

Browse files
authored
fix(reporter/http): read response body (#2108)
1 parent 0ec945d commit 40e36cc

File tree

1 file changed

+20
-6
lines changed

1 file changed

+20
-6
lines changed

reporter/http.go

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@ package reporter
33
import (
44
"bytes"
55
"encoding/json"
6+
"io"
67
"net/http"
78

8-
"github.com/future-architect/vuls/models"
99
"golang.org/x/xerrors"
10+
11+
"github.com/future-architect/vuls/models"
1012
)
1113

1214
// HTTPRequestWriter writes results to HTTP request
@@ -19,11 +21,20 @@ func (w HTTPRequestWriter) Write(rs ...models.ScanResult) (err error) {
1921
for _, r := range rs {
2022
b := new(bytes.Buffer)
2123
if err := json.NewEncoder(b).Encode(r); err != nil {
22-
return err
24+
return xerrors.Errorf("Failed to encode scan result. err: %w", err)
2325
}
24-
_, err = http.Post(w.URL, "application/json; charset=utf-8", b)
26+
27+
resp, err := http.Post(w.URL, "application/json; charset=utf-8", b)
2528
if err != nil {
26-
return err
29+
return xerrors.Errorf("Failed to post request. err: %w", err)
30+
}
31+
if resp.StatusCode != http.StatusOK {
32+
return xerrors.Errorf("Failed to post request. err: error request response with status code %d", resp.StatusCode)
33+
}
34+
defer resp.Body.Close()
35+
36+
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
37+
return xerrors.Errorf("Failed to discard response body. err: %w", err)
2738
}
2839
}
2940
return nil
@@ -41,7 +52,10 @@ func (w HTTPResponseWriter) Write(rs ...models.ScanResult) (err error) {
4152
return xerrors.Errorf("Failed to marshal scan results: %w", err)
4253
}
4354
w.Writer.Header().Set("Content-Type", "application/json")
44-
_, err = w.Writer.Write(res)
4555

46-
return err
56+
if _, err = w.Writer.Write(res); err != nil {
57+
return xerrors.Errorf("Failed to write response. err: %w", err)
58+
}
59+
60+
return nil
4761
}

0 commit comments

Comments
 (0)