Home  >  Article  >  Backend Development  >  How to Share a MySQL Connection Handle Between Go HTTP Handlers?

How to Share a MySQL Connection Handle Between Go HTTP Handlers?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 22:20:02803browse

How to Share a MySQL Connection Handle Between Go HTTP Handlers?

Managing MySQL Connections in Go HTTP Handlers

The database/sql package in Go handles database connections and automatically manages connection pooling. When invoking sql.Open(), it returns a handle that manages a connection pool. This handle establishes new connections as needed, ensuring there's always an available connection for database operations.

Sharing the Database Connection Handle

In your code, you've created a global variable db of type *sql.DB in the main() function. This variable represents the connection pool handle. To share it with the HTTP handlers, you can pass the db handle as a parameter to the handler functions.

Using the Connection Handle in HTTP Handlers

In the HomeHandler function, you can access the database connection by using the db handle that is passed as a parameter:

import (
    "database/sql"
    "fmt"
)

func HomeHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) {
    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)
    }
}

HTTP Handler Registration

In the main() function, when registering the HTTP handlers, you can pass the db handle as an argument:

import (
    "github.com/gorilla/mux"
)

func main() {
    fmt.Println("starting up")

    db, err := sql.Open("mysql", "root@unix(/tmp/mysql.sock)/mydb")
    if err != nil {
        log.Fatalf("Error on initializing database connection: %s", err.Error())
    }
    
    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler(db)) // Pass the db handle as an argument to the handler

    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}

By following these steps, you can effectively share the MySQL connection between HTTP goroutines in Go. The database/sql package's automatic connection pooling ensures optimal performance and resource management.

The above is the detailed content of How to Share a MySQL Connection Handle Between 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