Home >Backend Development >Golang >How to Share a MySQL Connection between HTTP Goroutines in Go?

How to Share a MySQL Connection between HTTP Goroutines in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-27 03:40:14340browse

How to Share a MySQL Connection between HTTP Goroutines in Go?

How to Share MySQL Connection between HTTP Goroutines?

In Go, the database/sql package simplifies the sharing of database connections between HTTP goroutines. By creating a connection pool, it automatically manages the opening and closing of database connections.

The sql.Open(...) function returns a connection pool handle, not just a single connection. The database/sql package handles opening new connections when the pool is fully utilized.

To share the database connection in the provided code sample, instantiate the db connection in the main() function and assign it to a global variable to facilitate its access by the HTTP handler.

var db *sql.DB // Global variable for sharing between main and HTTP handler

Then, in the main() function, use sql.Open(...) to initialize the connection pool. SetMaxIdleConns(...) configures the number of idle connections in the pool. A Ping() call ensures that a connection is established if needed.

func main() {
    var err error
    db, err = sql.Open("mysql", "root@unix(/tmp/mysql.sock)/mydb") // This opens a connection pool
    if err != nil {
        log.Fatalf("Error on initializing database connection: %s", err.Error())
    }

    db.SetMaxIdleConns(100)

    err = db.Ping() // This actually opens a connection if necessary
    if err != nil {
        log.Fatalf("Error on opening database connection: %s", err.Error())
    }
}

In the HomeHandler HTTP handler, use the global db variable to execute queries.

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    var msg string
    err := db.QueryRow("SELECT msg FROM hello WHERE page=?", "home").Scan(&msg)
    if err != nil {
        fmt.Fprintf(w, "Database Error!")
    } else {
        fmt.Fprintf(w, msg)
    }
}

By following this approach, the database connection can be shared efficiently among HTTP goroutines without the need for manual connection opening and closing.

The above is the detailed content of How to Share a MySQL Connection between HTTP Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn