Hello awesome Stackoverflow Community,
Apologies for the lame question. I was trying to find an answer to this question for some time, and googling didn't help me much.
I was playing around with Go's net/http
package and was following an article on organising *sql.Db
After going through it, I was trying to get two *sql.Db
types, one for master and one for slave. My intention was, for a simple route /home
, if the session
cookie is already set, use the master connection and let the connection go to the master server and use an RW user, and if not, use the slave connection with an RO user. I already have a wrapper struct DB
over *sql.DB
and a CheckSessionCookie method attached to it.
func (d *DB) CheckSessionCookie(w http.ResponseWriter, r *http.Request) (*http.Cookie) {
c, err := r.Cookie("session")
if err != nil {
return nil
}
return c
}
My routes looks like
http.HandleFunc("/admin", envMaster.Admin) // Master connection's method
http.HandleFunc("/home", envSlave.Home) // Slave connection's method
However, I cannot think of an elegant way to use a different handler func if the request has a cookie already set. I was thinking, if I could read the cookie with a javascript and pass the cookie as a parameter, and use the route as
http.HandleFunc("/home", envMaster.Home)
http.HandleFunc("/home/:session", envSlave.Home)
But I am not sure if that is a good way to do it, especially if http only
flag is set to the cookie.
How do I use a master connection if the request to "/home" has a session cookie already set?
Thank you.