John Cargo
John Cargo

Reputation: 2121

Avoid MySQL Connection during Websocket

I have a question regarding the flow of go lang code.

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.

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

Answers (1)

mkopriva
mkopriva

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

Related Questions