-
Notifications
You must be signed in to change notification settings - Fork 3
/
mdb.go
64 lines (52 loc) · 1.3 KB
/
mdb.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
)
type MultiDatabase struct {
addr string
dsn string
}
type MultiDatabaseRequest struct {
Dsn string `json:"dsn"`
SqlText string `json:"sql_text"`
Binds []interface{} `json:"binds"`
}
type MultiDatabaseResult struct {
Code int `json:"code"`
Dsn string `json:"dsn"`
Error string `json:"error"`
Result []map[string]interface{} `json:"result"`
}
func (md MultiDatabase) Ping() error {
_, err := md.Query("select * from dual")
return err
}
func (md MultiDatabase) Query(sqlText string) ([]map[string]interface{}, error) {
json_data, err := json.Marshal(MultiDatabaseRequest{md.dsn, sqlText, []interface{}{}})
if err != nil {
return nil, err
}
url := fmt.Sprintf("http://%s/query", md.addr)
// resp, err := http.Post(url, "application/json",
// bytes.NewBuffer(json_data))
req, err := http.NewRequest("POST", url, bytes.NewBuffer(json_data))
if err != nil {
return nil, err
}
c := http.DefaultClient
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var mdr MultiDatabaseResult
json.NewDecoder(resp.Body).Decode(&mdr)
if mdr.Code == 1 {
return nil, errors.New(mdr.Error)
}
return mdr.Result, nil
}