I separated different http.HandleFunc
in different files according to which page they are related to. I use gorilla/sessions
to manage client sessions and user authentication and I use go-sql-driver
for accessing a MySQL database.
Project Layout:
<PROJECT ROOT>
-> <cliend> // This folder containing html, css, and js
-> <pagehndler>
-> <index>
-> index.go // Need to access database and session
-> <projbrwsr>
-> projbrwsr.go // Need to access database and session
-> main.go
Therefore, I have 1 pointer pointing to the go-sql-driver
service
db, err := sql.Open("mysql", "user:password@/dbname")
and 1 pointer pointing to gorilla/sessions
service
var store = sessions.NewCookieStore([]byte("something-very-secret"))
There are 2 methods to pass the two pointers to other packages in my understanding:
Wrap the two pointers into two packages (sess
, db
) and make them exported. And, the package that requires the service needed to import the packages (sess
, db
). And call the exported pointers.
<PROJECT ROOT>
-> <cliend> // This folder containing html, css, and js
-> <pagehndler>
-> <index>
-> index.go // Need to access database and session
-> <projbrwsr>
-> projbrwsr.go // Need to access database and session
-> <service>
-> sess.go // Storing the database service pointer
-> db.go // Storing the session service pointer
-> main.go
Initialize the two pointers in main package and pass them to the another package, that contain the page handle functions, as args. Inside the another package, set the args to a local variable so we can call it locally in the another package.
<PROJECT ROOT>
-> <cliend> // This folder containing html, css, and js
-> <pagehndler>
-> <index>
-> index.go // Need to access database and session
// Containing a func newService(db *DB)
-> <projbrwsr>
-> projbrwsr.go // Need to access database and session
// Containing a func newService(sess *CookieStore)
-> main.go
What is the best way to pass this two pointers to other packages for other handle function to call them?
This is the concept which should work.
Inside the package you should declare a variable, which is exported. This variable has to be a pointer.
var myVar = 3
var MyPointer = &myVar
https://play.golang.org/p/EQDwGF7pjv
From your main package you can set the pointer to your "global" db or session adress.
mypackage.MyPointer = dbPointer
Then the pointer inside your package points to your dbPointer. I think this is a good way to pass a pointer into other packages.