-
Notifications
You must be signed in to change notification settings - Fork 17
/
client.go
84 lines (72 loc) · 1.78 KB
/
client.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
package search
import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
)
// decodeJson response
func (search *Search) decodeJSON(body io.ReadCloser) (SearchResult, error) {
// Decode JSON from response body
decoder := json.NewDecoder(body)
// Response data
var rsp SearchResult
err := decoder.Decode(&rsp)
if err != nil {
return nil, errors.New("fail to decode")
}
// check error message
errorMessage, derror := rsp["error"].(string)
if derror {
return nil, errors.New(errorMessage)
}
return rsp, nil
}
// decodeJSONArray decodes response body to SearchResultArray
func (search *Search) decodeJSONArray(body io.ReadCloser) (SearchResultArray, error) {
decoder := json.NewDecoder(body)
var rsp SearchResultArray
err := decoder.Decode(&rsp)
if err != nil {
return nil, errors.New("fail to decode array")
}
return rsp, nil
}
// decodeHTML decodes response body to html string
func (search *Search) decodeHTML(body io.ReadCloser) (*string, error) {
buffer, err := ioutil.ReadAll(body)
if err != nil {
return nil, err
}
text := string(buffer)
return &text, nil
}
// execute HTTP get reuqest and returns http response
func (search *Search) execute(path string, output string) (*http.Response, error) {
query := url.Values{}
if search.Parameter != nil {
for k, v := range search.Parameter {
query.Add(k, v)
}
}
// api_key
if len(search.ApiKey) != 0 {
query.Add("api_key", search.ApiKey)
}
// engine
if len(query.Get("engine")) == 0 {
query.Set("engine", search.Engine)
}
// source programming language
query.Add("source", "go")
// set output
query.Add("output", output)
endpoint := "https://serpapi.com" + path + "?" + query.Encode()
rsp, err := search.HttpSearch.Get(endpoint)
if err != nil {
return nil, err
}
return rsp, nil
}