Skip to content

Instantly share code, notes, and snippets.

@jordic
Created May 27, 2014 14:03
Show Gist options
  • Save jordic/3f118be0e5d59aa8b0fc to your computer and use it in GitHub Desktop.
Save jordic/3f118be0e5d59aa8b0fc to your computer and use it in GitHub Desktop.
golang mysql throught a tunnel
package main
// based on gist
// https://gist.github.com/ir4y/11146415
// http://stackoverflow.com/questions/21417223/simple-ssh-port-forward-in-golang
// obro conexio ssh amb el server remot.
// tot el que envio al port local ho copio al port remote
// a traves de la conexio remota. Per tant he d'obrir un
// port a la maquina remota?
import (
"code.google.com/p/go.crypto/ssh"
"database/sql"
"fmt"
_ "github.com/hgfischer/mysql"
"io"
"log"
"net"
)
func main() {
config := &ssh.ClientConfig{
User: "user",
Auth: []ssh.AuthMethod{
ssh.Password("password"),
},
}
// remote connection
conn, err := ssh.Dial("tcp", "ipadress:22", config)
if err != nil {
log.Fatalf("Unable to connect %s", err)
}
defer conn.Close()
// local connection
remote, err := conn.Dial("tcp", "localhost:3306")
if err != nil {
log.Fatalf("Unable to connect %s", err)
}
defer remote.Close()
local, err := net.Listen("tcp", "localhost:3306")
if err != nil {
log.Fatalf("Unable to connect %s", err)
}
defer local.Close()
go func() {
for {
l, err := local.Accept()
if err != nil {
log.Fatalf("listen Accept failed %s", err)
}
go func() {
_, err := io.Copy(l, remote)
if err != nil {
log.Fatalf("io.Copy failed: %v", err)
}
}()
go func() {
_, err := io.Copy(remote, l)
if err != nil {
log.Fatalf("io.Copy failed: %v", err)
}
}()
}
}()
dsn := "user:pass@tcp(127.0.0.1:3306)/bdd?charset=utf8"
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("Error connecting to database %s", err)
}
var count uint64
row := db.QueryRow("SELECT COUNT(*) FROM auth_user")
err = row.Scan(&count)
if err != nil {
log.Fatalf("Error on query database %s", err)
}
fmt.Printf("total registros %d", count)
//fmt.Printfln("Total %d", count)
}
@kelwang
Copy link

kelwang commented Jun 22, 2015

local, err := net.Listen("tcp", "localhost:3306")
works well in local address,
if you would like to bind a remote address or some other port. something like "mydomain.com:3307"
do
local, err := net.Listen("unix", "mydomain.com:3307")
and in the myslq connection
dsn := "user:pass@unix(mydomain:3307)/bdd?charset=utf8"

@kevinpostal
Copy link

Any idea how to do a remote port forwarding?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment