-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
61 lines (53 loc) · 1.5 KB
/
api.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
package search
import (
"fmt"
"github.com/PuerkitoBio/goquery"
"io"
"net/http"
"os"
"strings"
)
const apiURL = "https://pkg.go.dev/search?limit=50&m=package&q="
type Package struct {
Name string `json:"name,omitempty"`
Path string `json:"path"`
ImportCount int `json:"import_count"`
Synopsis string `json:"synopsis,omitempty"`
Fork bool `json:"fork,omitempty"`
Stars int `json:"stars,omitempty"`
Score float64 `json:"score,omitempty"`
}
type Response struct {
Results []Package `json:"results"`
}
func doSearch(pkg string) ([]Package, error) {
url := fmt.Sprintf("%s%s", apiURL, pkg)
var resp, err = http.DefaultClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
io.Copy(os.Stderr, resp.Body)
return nil, fmt.Errorf("failed to search package, server return code=%s", resp.Status)
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
var pkgs []Package
doc.Find(".go-Content.SearchResults .SearchSnippet").Each(func(i int, selection *goquery.Selection) {
path := removeQuote(selection.Find(".SearchSnippet-header-path").Text())
desc := removeQuote(selection.Find(".SearchSnippet-header-path").Text())
pkgs = append(pkgs, Package{
Name: path,
Path: path,
Synopsis: desc,
})
})
return pkgs, nil
}
var _replacer = strings.NewReplacer("(", "", ")", "", " ", "")
func removeQuote(s string) string {
return _replacer.Replace(s)
}