-
Notifications
You must be signed in to change notification settings - Fork 0
/
vendor.go
56 lines (46 loc) · 1.14 KB
/
vendor.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
package scanner
import (
"errors"
"fmt"
"io"
"log"
"net/http"
)
const DefaultVendor = "Unknown"
const VendorNameEndPoint = "https://macvendors.co/api/vendorname/%s"
type VendorFinder struct {
cache map[string]string
}
func NewVendorFinder() *VendorFinder {
return &VendorFinder{
cache: make(map[string]string),
}
}
func (f *VendorFinder) Find(hwAddress string) string {
name, ok := f.cache[hwAddress]
if ok {
return name
}
log.Printf("Vendor cache miss: %s not found, invoking 3rd party api", hwAddress)
name, err := getVendor(hwAddress)
if err != nil {
log.Printf("Name for %s address not found, fallback to %s, error %v", hwAddress, DefaultVendor, err)
return DefaultVendor
}
f.cache[hwAddress] = name
return name
}
func getVendor(addr string) (string, error) {
resp, err := http.Get(fmt.Sprintf(VendorNameEndPoint, addr))
if err != nil || resp.StatusCode >= 300 {
return "", errors.New("error on vendor api call")
}
defer func(body io.ReadCloser) {
_ = body.Close()
}(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", errors.New("bad response from vendor api")
}
return string(body), nil
}