-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathduckduckgolang.go
104 lines (90 loc) · 2.54 KB
/
duckduckgolang.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package duckduckgo
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type Client struct {
AppName string
}
type QueryResult struct {
Query string
EscapedQuery string
Answer string `json:"Answer"`
Results []Result `json:"Results"`
RelatedTopics []RelatedTopic `json:"RelatedTopics"`
InfoboxObj Infobox `json:"Infobox"`
InfoboxStr string `json:"Infobox"`
ImageIsLogoInt int `json:"ImageIsLogo"`
ImageIsLogoStr string `json:"ImageIsLogo"`
Definition string `json:"Definition"`
DefinitionURL string `json:"DefinitionURL"`
DefinitionSource string `json:"DefinitionSource"`
Heading string `json:"Heading"`
Image string `json:"Image"`
ImageWidthStr string `json:"ImageWidth"`
ImageHeightStr string `json:"ImageHeight"`
ImageWidthInt int `json:"ImageWidth"`
ImageHeightInt int `json:"ImageHeight"`
Abstract string `json:"Abstract"`
AbstractText string `json:"AbstractText"`
AbstractURL string `json:"AbstractURL"`
AbstractSource string `json:"AbstractSource"`
Type string `json:"Type"`
AnswerType string `json:"AnswerType"`
Entity string `json:"Entity"`
Redirect string `json:"Redirect"`
//Meta Meta `json:"meta"` //This will be added at a later date when all fields are known
}
type Result struct {
Result string `json:"Result"`
Icon Icon `json:"Icon"`
FirstURL string `json:"FirstURL"`
Text string `json:"Text"`
}
type RelatedTopic struct {
Text string `json:"Text"`
FirstURL string `json:"FirstURL"`
Result string `json:"Result"`
Icon Icon `json:"Icon"`
}
type Icon struct {
URL string `json:"URL"`
WidthStr string `json:"Width"`
HeightStr string `json:"Height"`
WidthInt int `json:"Width"`
HeightInt int `json:"Height"`
}
type Infobox struct {
Content []Content `json:"content"`
}
type Content struct {
ValueText string `json:"value"`
ValueObj Value `json:"value"`
Label string `json:"label"`
WikiOrderStr string `json:"wiki_order"`
WikiOrderInt int `json:"wiki_order"`
}
type Value struct {
EntityType string `json:"entity-type"`
ID string `json:"id"`
NumericID int `json:"numeric-id"`
}
func (c *Client) GetQueryResult(query string) (*QueryResult, error) {
escapedQuery := url.QueryEscape(query)
url := fmt.Sprintf("http://api.duckduckgo.com/?q=%s&format=json&t=%s", escapedQuery, c.AppName)
data := &QueryResult{}
data.Query = query
data.EscapedQuery = escapedQuery
res, err := http.Get(url)
if err != nil {
return nil, err
}
err = unmarshal(res, data)
return data, err
}
func unmarshal(body *http.Response, target interface{}) error {
defer body.Body.Close()
return json.NewDecoder(body.Body).Decode(target)
}