-
Notifications
You must be signed in to change notification settings - Fork 139
/
google.go
53 lines (44 loc) · 1.24 KB
/
google.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
package handler
import (
"context"
"strings"
"github.com/micro/micro/v3/service/errors"
"github.com/micro/micro/v3/service/logger"
pb "github.com/micro/services/google/proto"
"google.golang.org/api/customsearch/v1"
"google.golang.org/api/option"
)
type Google struct {
Client *customsearch.Service
CxId string
}
func New(apiKey, cxId string) *Google {
ctx := context.TODO()
cs, _ := customsearch.NewService(ctx, option.WithAPIKey(apiKey))
return &Google{
Client: cs,
CxId: cxId,
}
}
func (g *Google) Search(ctx context.Context, req *pb.SearchRequest, rsp *pb.SearchResponse) error {
if len(req.Query) == 0 {
return errors.BadRequest("google.search", "missing query")
}
resp, err := g.Client.Cse.List().Cx(g.CxId).Q(req.Query).Num(10).Do()
if err != nil {
logger.Errorf("failed to search google for %v: %v", req.Query, err)
return errors.InternalServerError("google.search", "Failed to search for "+req.Query)
}
for _, item := range resp.Items {
kind := strings.Split(item.Kind, "#")[1]
rsp.Results = append(rsp.Results, &pb.SearchResult{
Id: item.CacheId,
Kind: kind,
Title: item.Title,
Url: item.Link,
DisplayUrl: item.DisplayLink,
Snippet: item.Snippet,
})
}
return nil
}