Golang : Pass database connection to function called from another package and HTTP Handler
For this tutorial, we will explore how to pass database connection to external function called from another package. To pass a database connection is simple, just treat the database connection as a variable and at the function located in package, use pointer to point to the database connection variable. This tutorial will also cover how to pass database connection to HTTP Handler function as well.
Here we go!
package main
import (
"database/sql"
"fmt"
// without the underscore _, you will get imported but not
// used error message
_ "github.com/go-sql-driver/mysql"
"mypackage/myfunction"
"os"
)
func main() {
conn, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Pass conn (sql.DB type variable) to external function
myfunction.PrintTitles(conn)
conn.Close()
}
and then in the external function, remember to use *sql.DB
package myfunction
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"os"
)
func PrintTitles(conn *sql.DB) {
// use your own select statement
// this is just an example statement
statement, err := conn.Prepare("select blogtitle from blogs limit 10")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
rows, err := statement.Query() // execute our select statement
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for rows.Next() {
var blogtitle string
rows.Scan(&blogtitle)
fmt.Println("Title :", blogtitle)
}
}
and if you are calling your external function with HTTP Handler, such as :
mx := mux.NewRouter()
mx.HandleFunc("/", PrintTitles(conn))
then you need to wrap your function with a closure. So, instead of :
func PrintTitles(conn *sql.DB) (w http.ResponseWriter, r *http.Request) {
...
}
wrap(close) it with a anonymous function
func PrintTitles(conn *sql.DB) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
...
// can access conn variable now
}
}
Happy coding!
References :
https://www.socketloop.com/tutorials/golang-call-function-from-another-package
https://www.socketloop.com/tutorials/golang-connect-to-database-mysql-mariadb-server
See also : Golang : Call function from another package
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.4k Golang : Check if password length meet the requirement
+13.2k Golang : Get user input until a command or receive a word to stop
+9.2k Golang : How to extract video or image files from html source code
+5.7k PHP : How to check if an array is empty ?
+18.3k Golang : Generate thumbnails from images
+7.5k Golang : Reverse a string with unicode
+18.1k Golang : Get download file size
+5.3k Golang : Stop goroutine without channel
+18.1k Golang : Read binary file into memory
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+12.3k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+8.1k Your page has meta tags in the body instead of the head