-
Notifications
You must be signed in to change notification settings - Fork 3
/
search.go
63 lines (54 loc) · 1.36 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
package pork
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/mspaulding06/nap"
"github.com/spf13/cobra"
)
type SearchResponse struct {
Results []*SearchResult `json:"items"`
}
type SearchResult struct {
FullName string `json:"full_name"`
}
var SearchCmd = &cobra.Command{
Use: "search",
Short: "search for GitHub repositories by keyword",
Run: func(cmd *cobra.Command, args []string) {
if err := SearchByKeyword(args); err != nil {
log.Fatalln("Search Failed:", err)
}
},
}
func SearchByKeyword(keywords []string) error {
return GitHubAPI().Call("search", map[string]string{
"query": strings.Join(keywords, "+"),
}, nil)
}
func SearchSuccess(resp *http.Response) error {
defer resp.Body.Close()
content, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
respContent := SearchResponse{}
json.Unmarshal(content, &respContent)
for _, item := range respContent.Results {
fmt.Println(item.FullName)
}
return nil
}
func SearchDefaultRouter(resp *http.Response) error {
return fmt.Errorf("status code %d", resp.StatusCode)
}
func GetSearchResource() *nap.RestResource {
searchRouter := nap.NewRouter()
searchRouter.DefaultRouter = SearchDefaultRouter
searchRouter.RegisterFunc(200, SearchSuccess)
search := nap.NewResource("/search/repositories?q={{.query}}", "GET", searchRouter)
return search
}