-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaviasales-api.go
113 lines (98 loc) · 2.28 KB
/
aviasales-api.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
105
106
107
108
109
110
111
112
113
package aviasales
import (
"compress/gzip"
"encoding/json"
"encoding/xml"
"net/http"
"net/url"
)
type AviasalesApi struct {
token string
log LoggerInterface
}
type LoggerInterface interface {
Debug(...interface{})
}
// NewAviasalesApi creates a new instance AviasalesApi.
func NewAviasalesApi(token string) *AviasalesApi {
return &AviasalesApi{
token: token,
}
}
type Coordinates struct {
Lon float64 `json:"lon" bson:"lon"`
Lan float64 `json:"lat" bson:"lat"`
}
func (a *AviasalesApi) SetLogger(logger LoggerInterface) {
a.log = logger
}
func (a *AviasalesApi) getJson(path string, args map[string]string, v interface{}) error {
apiUrl, err := url.Parse("http://api.travelpayouts.com/" + path)
if err != nil {
return err
}
params := url.Values{}
for k, v := range args {
if v == "" {
continue
}
params.Add(k, v)
}
apiUrl.RawQuery = params.Encode()
if a.log != nil {
a.log.Debug("API Send: " + apiUrl.String())
}
client := &http.Client{}
req, _ := http.NewRequest("GET", apiUrl.String(), nil)
req.Header.Set("Accept-Encoding", "gzip, deflate")
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.Header.Get("Content-Encoding") == "gzip" {
// decompress data
reader, err := gzip.NewReader(res.Body)
if err != nil {
return err
}
defer reader.Close()
return json.NewDecoder(reader).Decode(&v)
}
return json.NewDecoder(res.Body).Decode(&v)
}
func (a *AviasalesApi) getXML(path string, args map[string]string, v interface{}) error {
apiUrl, err := url.Parse("http://api.travelpayouts.com/" + path)
if err != nil {
return err
}
params := url.Values{}
for k, v := range args {
if v == "" {
continue
}
params.Add(k, v)
}
apiUrl.RawQuery = params.Encode()
if a.log != nil {
a.log.Debug("API Send: " + apiUrl.String())
}
client := &http.Client{}
req, _ := http.NewRequest("GET", apiUrl.String(), nil)
req.Header.Set("Accept-Encoding", "gzip, deflate")
res, err := client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if res.Header.Get("Content-Encoding") == "gzip" {
// decompress data
reader, err := gzip.NewReader(res.Body)
if err != nil {
return err
}
defer reader.Close()
return xml.NewDecoder(reader).Decode(&v)
}
return xml.NewDecoder(res.Body).Decode(&v)
}