Search code examples
gogo-gorm

How do I connect database via ssh using gorm in golang?


I am trying to connect to database via ssh, I am using the database/sql package to connect to the database, but I don't understand how to implement the database/sql to the gorm jinzhu/gorm. Can somebody tell me how to implement it? Or is there any way to connect by just using gorm package? I am fairly new to golang.

This is what the code looks like. The main problem is in NewBrandsRepository method which cannot use type *sql.DB as *gorm.DB

// Connect to the SSH Server
sshcon, errSSH := ssh.Dial("tcp", fmt.Sprintf("%s:%d", sshHost, sshPort), sshConfig)
if errSSH != nil {

}

defer sshcon.Close()

// Now we register the ViaSSHDialer with the ssh connection as a parameter
mysql.RegisterDial("mysql+tcp", (&ViaSSHDialer{sshcon}).Dial)

// And now we can use our new driver with the regular mysql connection string tunneled through the SSH connection
db, errDB := sql.Open("mysql", fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName))

if errDB != nil {

    fmt.Printf("Failed to connect to the db: %s\n", errDB.Error())

}

fmt.Printf("Successfully connected to the db\n")

test := NewBrandsRepository(db)

and the NewBrandsRepository method is this

type brandsRepositoryImpl struct {
    db *gorm.DB
}

func NewBrandsRepository(db *gorm.DB) *brandsRepositoryImpl {
    return &brandsRepositoryImpl{db}
}

Solution

  • Keep doing the same steps but instead of sql.Open use

    dsn := fmt.Sprintf("%s:%s@mysql+tcp(%s)/%s", dbUser, dbPass, dbHost, dbName)
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})