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?