-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
220 lines (193 loc) · 4.85 KB
/
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
package connectors
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"time"
)
type RestAPI struct {
Url *url.URL
Email string
Password string
Session *http.Client
}
type Record struct {
Fields []interface{}
}
type ColumnType struct {
ColumnName string
ColumnType string
}
type Response struct {
Type string `json:"type"`
Error string `json:"error_message"`
Data interface{} `json:"data"`
}
func GetSessionId(resp *http.Response) string {
for _, cookie := range resp.Cookies() {
if cookie.Name == "session" {
return cookie.Value
}
}
return ""
}
func Login(email, password string) (*RestAPI, error) {
api := RestAPI{}
apiUrl, err := url.Parse("https://cloud.mindsdb.com")
api.Url = apiUrl
api.Email = email
api.Password = password
jsonStr, _ := json.Marshal(map[string]string{
"email": api.Email,
"password": api.Password,
})
api.Session = &http.Client{
Timeout: time.Second * 10,
}
empty_api := RestAPI{}
url := fmt.Sprintf("%s/cloud/login", api.Url.String())
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(string(jsonStr)))
if err != nil {
return &empty_api, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := api.Session.Do(req)
if err != nil {
return &empty_api, err
}
var r Response
err = json.NewDecoder(resp.Body).Decode(&r)
if err != nil {
return &empty_api, err
}
session_id := GetSessionId(resp)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return &empty_api, fmt.Errorf("Login failed: %s", resp.Status)
}
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
cookie := &http.Cookie{
Name: "session",
Value: session_id,
}
client := &http.Client{Timeout: time.Second * 60, Jar: jar}
client.Jar.SetCookies(api.Url, []*http.Cookie{cookie})
api.Session = client
return &api, nil
}
func (api *RestAPI) SqlQuery(session *http.Client, sql string, database string, lowercaseColumns bool) (data []Record, columns []ColumnType, err error) {
if database == "" {
database = "mindsdb"
}
body, err := PostQuery(*api, database, sql)
return ReadRowColumns(body)
}
func PostQuery(api RestAPI, database, sql string) ([]byte, error) {
url := fmt.Sprintf("%s/api/sql/query", api.Url.String())
jsonStr, err := json.Marshal(map[string]interface{}{
"query": sql,
"context": map[string]string{"db": database},
})
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := api.Session
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API call failed with status code %d", resp.StatusCode)
}
return body, nil
}
func ReadRowColumns(body []byte) (data []Record, columns []ColumnType, err error) {
var result map[string]interface{}
err = json.Unmarshal(body, &result)
if err != nil {
return nil, nil, err
}
var columnNames []string
if columnsArr, ok := result["column_names"].([]interface{}); ok {
for _, column := range columnsArr {
if columnStr, ok := column.(string); ok {
columnNames = append(columnNames, strings.ToLower(columnStr))
}
}
}
var records []Record
if dataArr, ok := result["data"].([]interface{}); ok {
for i, row := range dataArr {
if rowMap, ok := row.([]interface{}); ok {
record := Record{
Fields: make([]interface{}, len(columns)),
}
for j, value := range rowMap {
record.Fields = append(record.Fields, value)
if i == 0 {
col := ColumnType{ColumnName: columnNames[j], ColumnType: fmt.Sprintf("%T", record.Fields[j])}
columns = append(columns, col)
}
}
records = append(records, record)
}
}
}
return records, columns, nil
}
func (api *RestAPI) APIRequest(database, method, endpoint string, body map[string]string) ([]byte, error) {
apiUrl := api.Url.String()
Url, err := url.Parse(apiUrl + endpoint)
if err != nil {
return nil, err
}
var jsonStr []byte
if method == "POST" {
jsonStr, err = json.Marshal(map[string]interface{}{
"database": body,
})
if err != nil {
return nil, err
}
} else if method == "GET" {
jsonStr = nil
}
req, err := http.NewRequest(method, Url.String(), bytes.NewBuffer(jsonStr))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := api.Session
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API call failed with status code %d", resp.StatusCode)
}
return respBody, nil
}