/
api-fetch.go
79 lines (63 loc) · 1.28 KB
/
api-fetch.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package database
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"path"
)
func (db APIDB) osvEndpoint(id string) string {
u := *db.BaseURL
u.Path = path.Join(u.Path, "vulns", id)
return u.String()
}
// Fetch gets the details of a specific OSV from the osv.dev database
func (db APIDB) Fetch(id string) (OSV, error) {
var osv OSV
req, err := http.NewRequestWithContext(
context.Background(),
http.MethodGet,
db.osvEndpoint(id),
http.NoBody,
)
if err != nil {
return osv, fmt.Errorf("%w: %w", ErrAPIRequestInvalid, err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return osv, fmt.Errorf("%w: %w", ErrAPIRequestFailed, err)
}
defer resp.Body.Close()
var body []byte
body, err = io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
return osv, fmt.Errorf(
"%w (%s %s %d)",
ErrAPIUnexpectedResponse,
resp.Request.Method,
resp.Request.URL,
resp.StatusCode,
)
}
if err != nil {
return osv, fmt.Errorf(
"%w (%s %s): %w",
ErrAPIUnreadableResponse,
resp.Request.Method,
resp.Request.URL,
err,
)
}
err = json.Unmarshal(body, &osv)
if err != nil {
return osv, fmt.Errorf(
"%w (%s %s): %w",
ErrAPIResponseNotJSON,
resp.Request.Method,
resp.Request.URL,
err,
)
}
return osv, nil
}