-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsearch.go
70 lines (55 loc) · 1.54 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
package ratings
import (
"context"
"os"
log "github.com/sirupsen/logrus"
search "google.golang.org/api/customsearch/v1"
"google.golang.org/api/option"
)
func getBookDetailsFromSearch(book, site string) (*search.Result, error) {
searchService, err := search.NewService(context.Background(), option.WithAPIKey(os.Getenv("SEARCH_API_KEY")))
if err != nil {
log.WithFields(log.Fields{
"err": err.Error(),
"book": book,
"site": site,
}).Error("Could not form new search service)")
return nil, err
}
searchID := os.Getenv(searchIDEnvVariableNames[site])
if searchID == "" {
log.WithFields(log.Fields{
"book": book,
"site": site,
}).Error("Could not get search ID for site)")
return nil, err
}
res, err := getFirstSearchResult(book, searchID, searchService)
if err != nil {
return nil, err
}
return res, nil
}
func getFirstSearchResult(book, searchID string, searchService *search.Service) (*search.Result, error) {
searchCall := searchService.Cse.List()
searchCall.Q(book)
searchCall.Cx(searchID)
searchResults, err := searchCall.Do()
if err != nil {
log.WithFields(log.Fields{
"err": err.Error(),
"book": book,
"searchID": searchID,
}).Error("Could not get search results after searching for book in site)")
return nil, err
}
if len(searchResults.Items) == 0 {
log.WithFields(log.Fields{
"err": err.Error(),
"book": book,
"searchID": searchID,
}).Error("Got zero search results after searching for book in site)")
return nil, err
}
return searchResults.Items[0], nil
}