How to Share a MySQL Connection Across Go HTTP Handlers?

Patricia Arquette
Release: 2024-11-12 21:42:02
Original
960 people have browsed it

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")
Copy after login

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)
Copy after login

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

err = db.Ping()
Copy after login

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
Copy after login

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)
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template