/
search.go
73 lines (61 loc) · 1.69 KB
/
search.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
package pkgmgmt
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sort"
"strings"
"github.com/pkg/errors"
)
// Searcher contains a packr.Box containing a searchable list of packages
type Searcher struct {
List PackageList
}
// NewSearcher returns a Searcher with the provided packr.Box
func NewSearcher(list PackageList) Searcher {
return Searcher{
List: list,
}
}
// Search searches for packages matching the optional provided name,
// returning the full list if none is provided
func (s *Searcher) Search(name, pkgType string) (PackageList, error) {
if name == "" {
sort.Sort(s.List)
return s.List, nil
}
results := PackageList{}
query := strings.ToLower(name)
for _, p := range s.List {
if strings.Contains(p.Name, query) {
results = append(results, p)
}
}
if results.Len() == 0 {
return PackageList{}, errors.Errorf("no %ss found for %s", pkgType, name)
}
sort.Sort(results)
return results, nil
}
// GetPackageListings returns the listings for packages via the provided URL
func GetPackageListings(url string) (PackageList, error) {
resp, err := http.Get(url)
if err != nil {
return PackageList{}, errors.Wrapf(err, "unable to fetch package list via %s", url)
}
if resp.StatusCode != http.StatusOK {
return PackageList{}, fmt.Errorf("unable to fetch package list via %s: %s", url, http.StatusText(resp.StatusCode))
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return PackageList{}, errors.Wrapf(err, "unable to read package list via %s", url)
}
list := PackageList{}
err = json.Unmarshal(data, &list)
if err != nil {
return PackageList{}, errors.Wrap(err, "unable to unmarshal package list")
}
return list, nil
}