forked from sbotman/go-training
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogle.go
89 lines (74 loc) · 2.32 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// All material is licensed under the GNU Free Documentation License
// Package search : google performs searches against the google search engine.
package search
import (
"encoding/json"
"log"
"net/http"
"strings"
)
// Google provides support for Google searches.
type Google struct{}
type (
// gResult maps to the result document received from the search.
gResult struct {
GsearchResultClass string `json:"GsearchResultClass"`
UnescapedURL string `json:"unescapedUrl"`
URL string `json:"url"`
VisibleURL string `json:"visibleUrl"`
CacheURL string `json:"cacheUrl"`
Title string `json:"title"`
TitleNoFormatting string `json:"titleNoFormatting"`
Content string `json:"content"`
}
// gResponse contains the top level document.
gResponse struct {
ResponseData struct {
Results []gResult `json:"results"`
} `json:"responseData"`
}
)
// NewGoogle returns a Google Searcher value.
func NewGoogle() Searcher {
return Google{}
}
// Search implements the Searcher interface. It performs a search
// against Google.
func (g Google) Search(searchTerm string, searchResults chan<- []Result) {
log.Printf("Google : Search : Started : searchTerm[%s]\n", searchTerm)
// Slice for the results.
var results []Result
// On return send the results we have.
defer func() {
log.Println("Google : Search : Info : Sending Results")
searchResults <- results
}()
// Build a proper search url.
searchTerm = strings.Replace(searchTerm, " ", "+", -1)
uri := "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=8&q=" + searchTerm
// Issue the search against Google.
resp, err := http.Get(uri)
if err != nil {
log.Printf("Google : Search : Get : ERROR : %s\n", err)
return
}
// Schedule the close of the response body.
defer resp.Body.Close()
// Decode the JSON response into our struct type.
var gr gResponse
err = json.NewDecoder(resp.Body).Decode(&gr)
if err != nil {
log.Printf("Google : Search : Decode : ERROR : %s\n", err)
return
}
// Capture the data we need for our results.
for _, result := range gr.ResponseData.Results {
results = append(results, Result{
Engine: "Google",
Title: result.Title,
Link: result.URL,
Content: result.Content,
})
}
log.Printf("Google : Search : Completed : Found[%d]\n", len(results))
}