-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathddgo.go
76 lines (61 loc) · 1.6 KB
/
ddgo.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
package ddgo
import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
)
// Result holds the returned query data
type Result struct {
Title string
Info string
Ref string
}
// Requests the query and puts the results into an array
func Query(query string, maxResult int) ([]Result, error) {
results := []Result{}
queryUrl := fmt.Sprintf("https://duckduckgo.com/html/?q=%s", url.QueryEscape(query))
response, err := http.Get(queryUrl)
if err != nil {
log.Printf("get %v error: %s", queryUrl, err)
return results, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
log.Printf("status code error: %d %s", response.StatusCode, response.Status)
return results, fmt.Errorf("status code error: %d %s", response.StatusCode, response.Status)
}
doc, err := goquery.NewDocumentFromReader(response.Body)
if err != nil {
log.Printf("NewDocument Error: %s", err)
return results, err
}
sel := doc.Find(".web-result")
for i := range sel.Nodes {
// Break loop once required amount of results are add
if maxResult == len(results) {
break
}
node := sel.Eq(i)
titleNode := node.Find(".result__a")
info := node.Find(".result__snippet").Text()
title := titleNode.Text()
ref := ""
if len(titleNode.Nodes) > 0 && len(titleNode.Nodes[0].Attr) > 2 {
ref, err = url.QueryUnescape(
strings.TrimPrefix(
titleNode.Nodes[0].Attr[2].Val,
"/l/?kh=-1&uddg=",
),
)
if err != nil {
log.Printf("Error: %s", err)
return results, err
}
}
results = append(results[:], Result{title, info, ref})
}
return results, nil
}