I had question about better code usage in golang.
What is the best case of usage live connection like database in few packages.
It is better to add database connection like
1.
func (database DB) getRows(){
}
or 2.
func getRows(database *DB){
}
or 3.
func getRows(){
init database connection...
}
For 1 usage we need create local struct for DB
type DB struct{
connection
}
in different package I need move DB connection with creating local struct in each package or when some package did not use database connection but imported package use? How to send one configuration and create only one connection? Singleton is good idea?
Are you have any tips and trick for this case usage?
A good practice is to pass a persistent DB around connection that is created on the start of your application. This connection will satisfy an interface for the subsequent DB calls that you make within your function. The reason you use an interface is to allow for interchanging the underlying DB and flexibility for testing within the application.
For this example I'm using the jmoiron/sqlx package.
package main
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron"
)
func main() {
// Connect to the DB to create the persistent connection.
db := connDB()
// The sqlx.DB connection returned will satisfy the DB interface.
name, err := getRows(db)
}
// DB is required for functions interfacing with the database.
type DB interface {
Get(dest interface{}, q string, args ...interface{}) error
Select(dest interface{}, q string, args ...interface{}) error
Exec(q string, args ...interface{}) (sql.Result, error)
}
// connDB connects to the database and returns an active connection.
func connDB() *sqlx.DB {
// Connect to the database and ping, confirming connection was made.
// Panic if the connection was not successful.
db, err := sqlx.Connect("mysql", "root:password@tcp(localhost)/default")
if err != nil {
panic(err)
}
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(60)
return db
}
// getRow will now be able to make DB calls.
func getRow(database DB) (string, error) {
var name string
q := `SELECT name FROM user WHERE id=?;`
if err := database.Get(&name, q, "user123"); err != nil {
return name, err
}
return name, nil
}