1

I would like to understand how does GIN ensures that each HTTP request gets a unique DB ( say MySQL ) connection. Here is one example code. If you see, since 'db' is a global object and therefore, the API router.GET("/person/:age"... gets access to DB. Now with load, I suppose GIN will have concurrency implemented internally. If yes, then how does it ensures that each request gets a different connection. If no, then it is single threaded imnplementation. Could anyone please correct my understanding.

package main

import (
    //  "bytes"
    "database/sql"
    "fmt"
    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
    "net/http"
)

func checkErr(err error) {
    if err != nil {
        panic(err)
    } else {
        fmt.Println("successful...")
    }
}

func main() {
    db, err := sql.Open("mysql", "abfl:abfl@tcp(127.0.0.1:3306)/abfl?charset=utf8")
    checkErr(err)
    defer db.Close()
    // make sure connection is available
    err = db.Ping()
    checkErr(err)
    type User struct {
        age  int
        name string
    }
    router := gin.Default()
    // Add API handlers here
    // GET a user detail
    router.GET("/person/:age", func(c *gin.Context) {
        var (
            user   User
            result gin.H
        )
        age := c.Param("age")
        fmt.Println("input age : '%d'", age)
        row := db.QueryRow("select age, name from user where age = ?", age)
        err = row.Scan(&user.age, &user.name)
        fmt.Printf("user : %+v\n", user)
        if err != nil {
            // If no results send null
            result = gin.H{
                "user":  nil,
                "count": 0,
            }
        } else {
            result = gin.H{
                "age":   user.age,
                "name":  user.name,
                "count": 1,
            }
        }
        c.JSON(http.StatusOK, result)
    })
    router.Run(":3000")
}
7
  • 2
    Please be sure to properly format code. As originally posted, it was completely unreadable. I edited it, but... in the future, please do this when posting. Commented Nov 29, 2017 at 4:10
  • Sure thanks. Why is my question given -2 :). Is it an invalid question ? Guys I am looking for an answer. Commented Nov 29, 2017 at 6:18
  • 1
    Why do you need separate connection for each request? In fact good framework can cache data so page loads can involve no database access. Also db driver has its own connection pool. So there’s no direct association between web and db requests. Commented Nov 29, 2017 at 7:22
  • 1
    I recommend you to get and read this ebook to gain deep understanding of how database/sql is implemented. (I'm not affilicated with the book's authors, FWIW.) Commented Nov 29, 2017 at 10:17
  • Great @kostix. This is quite helpful Commented Nov 30, 2017 at 8:28

1 Answer 1

1

Establishing a new SQL connection for each HTTP request is too heavy and has no sense.
In go there is no user-managable connection pool yet, it is handled internally by go implementation.
sql.DB is ready to be used concurrently, so there is no worry about it.
And GIN has nothing to do with SQL connections at all. It is fully your responsibility to handle queries/transactions properly.

Sign up to request clarification or add additional context in comments.

2 Comments

Here is copy-paste of my question mentioned above : what I am looking for is : how to utilise 'prepared-statement' with this framework ( gin ). I don't want to see it working because everytime the REST API call is preparing the statement. Which would be very in-efficient. The proper logic would be while creating prepared statement it should be tightly bound with the connection. Now if we use connection pool and we really want to utilise prep-stmt handle, then we should have a map of each stmt with unique db connection. Now question is : is it provided by GIN or not
No, it doesn't. Gin - is a web tool and does nothing with anything underneath HTTP transport layer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.