Aldy Yuan
Aldy Yuan

Reputation: 2065

How to open db connection only when there's request in golang

So what I'm gonna do is try to open db connection when there's is http request, and close again. I'm using pgx and gin package so here's what I do :

func handleGetUsers(c *gin.Context) {
connectDB()
data, err := allUsers()
if err != nil {
    log.Println(err)
    return
}

results := struct {
    Count int    `json:"count"`
    Data  []User `json:"data"`
}{
    Count: len(data),
    Data:  data,
}

c.JSON(200, results)
defer connectDB()

}

But if I'm trying to make another same http request, database connection already close. Is there something i can do or my logic was wrong after all

Upvotes: 0

Views: 904

Answers (1)

Mikhail Andrianov
Mikhail Andrianov

Reputation: 179

Probably, your intentions are little overhead.

Webserver executes Go function whenever you query your server's url. If that means doing an sql request - it will be executed and the connection will be closed. The webserver returns the result and the communication between your sever and client is over.

What I can suggest, since I believe you want to increase your gin-gonic performance is to use concurrent DB query execution in Gin.

    messages := make(chan string)
router.GET("/db_connection",func(c *gin.Context){

    c.Copy()

    go func(
        connectDB()
    <-messages
    ){}()

    data, err := allUsers()
    if err != nil {
        log.Println(err)
        return
    }

    results := struct {
        Count int    `json:"count"`
        Data  []User `json:"data"`
    }{
        Count: len(data),
        Data:  data,
    }

    c.JSON(200, results)
    go func(
        connectDB()
    <-messages
    ){}()




})

Upvotes: 1

Related Questions