0

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

oguz ismail
  • 1
  • 16
  • 47
  • 69
Aldy Yuan
  • 1,795
  • 9
  • 23

1 Answers1

1

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




})