Home >Backend Development >Golang >How to Share a MySQL Connection Across Go HTTP Handlers?

How to Share a MySQL Connection Across Go HTTP Handlers?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-12 21:42:021033browse

How to Share a MySQL Connection Across Go HTTP Handlers?

Sharing MySQL Connection in Go HTTP Handlers

In Go, managing database connections is made seamless with the database/sql package. This guide provides an in-depth overview of how to establish a MySQL connection and share it among your HTTP handlers.

Establishing the Connection

The main() function is responsible for initializing your database connection. Here, you call sql.Open(), which returns a connection pool handle, not a single connection. This handle encapsulates the logic for providing connections as needed, ensuring efficient resource utilization.

db, err := sql.Open("mysql", "root:@/mydb?charset=utf8")

Configuration and Ping

Once the connection pool is established, you can configure it to meet your application's needs. For instance, you can set the maximum number of idle connections in the pool:

db.SetMaxIdleConns(100)

To verify the availability of the database, you should perform a ping before proceeding:

err = db.Ping()

Sharing the Connection

The key to sharing the connection lies in making the db variable a global variable accessible to both main() and your HTTP handlers. This ensures that all goroutines can utilize the same connection pool.

var db *sql.DB // global variable to share between main and HTTP handlers

Using the Connection in HTTP Handlers

Within your HTTP handlers, you can interact with the database using the shared connection. For example, to retrieve data from the "hello" table:

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)
    }
}

The above is the detailed content of How to Share a MySQL Connection Across Go HTTP Handlers?. 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