Reputation: 2121
I have a question regarding the flow of go lang code.
In my main
function, I am opening mysql
connection and then using `defer" to close the connection at the end of the connection.
I have route
where WebSocket
is set up and used.
My Question is will program open connection every time, WebSocket is used to send and receive a message or will it just open once the page was loaded.
Here is how my code looks like:-
package main
import (
// Loading various package
)
func main() {
// Opening DB connection -> *sql.DB
db := openMySql()
// Closing DB connection
defer db.Close()
// Route for "websocket" end point
app.Get("/ws", wsHandler(db))
// Another route using "WebSocket" endpoint.
app.Get("/message", message(db))
}
Now, while a user is at "message
" route, whenever he is sending the message to other users, Will mysql
- open
and close
connection event will happen every time, when the message is being sent and receive using "/ws
" route?
Or will it happen Just once? whenever "/message
" route and "/ws
" event is called the first time.
My Purpose of using "db
" in "wsHandler
" function is to verify and check if the user has permission to send a message to the particular room or not.
But there is no point opening and closing connection every second while WebSocket
emits message
or typing
event.
What would be the best way to handle permission checking in "/ws" route, if above code is horror? Considering a fact there will be few hundred thousand concurrent users.
Upvotes: 0
Views: 440
Reputation: 38243
Assuming db
is *sql.DB your code seems fine, I'm also assuming that your example is incomplete and your main
does not actually return right away.
The docs on Open state:
The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.
So wsHandler
and message
should be ok to use it as they please as long as they don't close DB themselves.
Upvotes: 1