-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch.go
52 lines (42 loc) · 1.17 KB
/
fetch.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
package db
import (
"context"
"database/sql"
"github.com/go-sql-driver/mysql"
"golang.org/x/crypto/ssh"
"io/ioutil"
"net"
"strings"
)
var (
PrivateKeyFilename string = "ssh.pem"
)
func Fetch(uri string, query string, callback func(row *sql.Rows)) error {
mysqlDb, err := sql.Open("mysql", uri)
if err != nil { return err }
defer mysqlDb.Close()
rows, err := mysqlDb.Query(query)
if err != nil { return err }
for rows.Next() {
callback(rows)
}
return nil
}
func FetchSSH(sshUri string, uri string, query string, callback func(row *sql.Rows)) error {
pemBytes, err := ioutil.ReadFile(PrivateKeyFilename)
if err != nil { return err }
signer, err := ssh.ParsePrivateKey(pemBytes)
if err != nil { return err }
sshUriParts := strings.Split(sshUri, "@")
sshcon, err := ssh.Dial("tcp", sshUriParts[1], &ssh.ClientConfig {
User: sshUriParts[0],
Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
})
if err != nil { return err }
defer sshcon.Close()
mysql.RegisterDialContext("mysql+tcp", func(_ context.Context, addr string) (net.Conn, error) {
return sshcon.Dial("tcp", addr)
})
return Fetch(uri, query, callback)
}