Skip to content

Commit 6109cb6

Browse files
committed
Refactor PyPI with channel usage
1 parent 70efe4d commit 6109cb6

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

pkg/pypi/search.go

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,30 @@ const workerCount = 5
1717
func SearchByAPI(name string, max int) ([]model.PyPIPackageResult, error) {
1818
client := &http.Client{Timeout: 5 * time.Second}
1919

20-
b, err := util.RESTAPIQuery(client, listing())
20+
bl, err := util.RESTAPIQuery(client, listing())
2121
if err != nil {
2222
return []model.PyPIPackageResult{}, err
2323
}
2424

2525
var listingRes PypiListingResponse
26-
if err := json.Unmarshal(b, &listingRes); err != nil {
26+
if err := json.Unmarshal(bl, &listingRes); err != nil {
2727
return []model.PyPIPackageResult{}, err
2828
}
2929

30-
result := []model.PyPIPackageResult{}
30+
taskChan := make(chan string)
31+
go func() {
32+
for _, project := range listingRes.Projects {
33+
if strings.HasPrefix(project.Name, name) {
34+
taskChan <- project.Name
35+
}
36+
}
37+
close(taskChan)
38+
}()
3139

40+
result := []model.PyPIPackageResult{}
3241
count := 0
33-
for _, project := range listingRes.Projects {
34-
if !strings.HasPrefix(project.Name, name) {
35-
continue
36-
}
37-
bd, err := util.RESTAPIQuery(client, detail(project.Name))
42+
for pkg := range taskChan {
43+
bd, err := util.RESTAPIQuery(client, detail(pkg))
3844
if err != nil {
3945
continue
4046
}
@@ -50,7 +56,7 @@ func SearchByAPI(name string, max int) ([]model.PyPIPackageResult, error) {
5056
if len(author) == 0 {
5157
author = model.NoAuthor
5258
}
53-
result = append(result, model.PyPIPackageResult{Name: project.Name, Description: description, Author: author})
59+
result = append(result, model.PyPIPackageResult{Name: pkg, Description: description, Author: author})
5460
count++
5561
if count >= max {
5662
break

0 commit comments

Comments
 (0)