I have two packages, main and db.
However, I get "DB declared and not used" error.
db.go
package db
import (
"database/sql"
)
var DB *sql.DB
func Connect() {
DB, err := sql.Open("mysql", "root:xxxx@/xxxx")
if err != nil {
panic(err.Error())
}
}
func Close() {
DB.Close()
}
main.go
package main
import (
"database/sql"
// "fmt"
_ "github.com/go-sql-driver/mysql"
"html/template"
"net/http"
"github.com/****/****/config"
"github.com/****/****/db"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}
func main() {
Connect()
defer Close()
loadRoutes()
http.ListenAndServe(":8080", nil)
}
:=, the short variable declaration, which declares a newDBvariable for the scope of theConnectfunction. That means that theDBdeclared at the package level is a different variable from theDBdeclared insideConnect. To fix the problem, insideConnectjust abovesql.Open, declare an error variable (i.e.var err error) and then use=; i.e.DB, err = sql.Open(.... Example: play.golang.org/p/3XglGr-2LZa