来自不同文件的全局变量Golang

I have two different files: (1) /common/handler.go and (2) main.go.

In the (/common/handler.go) file, I have declared

var db *sql.DB
var err error

as global variables (at the top level, below import). Now, I want to use these two variables in my main.go file because I have this line of code in my main() function:

db, err = sql.Open("mysql","username:password@tcp(127.0.0.1:3306)/test123")

What should I do in order for Go to understand that I was referring to that db and err variables? Am I even doing this the right way? If not, please let me know the best solution.

The reason I split into these two files because I want to make the code cleaner.

Basically, main() in main.go contains

router := mux.NewRouter()
router.HandleFunc("/", common.login)
....

and handler.go contains all the messy stuff.

Thanks,

"I want to use these two variables in my main.go" You can't because they are unexported, ergo you need to export them.

"What should I do in order for Go to understand that I was referring to that db and err variables?" You need to qualify them. It's no different from you telling Go with sql.Open that you're referring to the function Open that's declared in the package database/sql.


Also I recommend you take the Tour of Go.