带有Postgres的Gorm客户问题过多

I have my database connection in my admin package setup like this,

Template File:

type Template struct{}

func NewAdmin() *Template {
   return &Template{}
}

Database File:

type Database struct {
   T *Template
}

func (admin *Database) DB() *gorm.DB {
    db, err := gorm.Open("postgres", "host=localhost port=5010 user=postgres dbname=postgres password=password sslmode=disable")

    if err != nil {
       panic(err)
    }

    return db
}

Now I using that connection in my controllers package, like so

Controller Teamplate

type Template struct {
  Connection *admin.Database
}

Profile File:

type ProfilesController struct {
  T *Template
}

func (c *ProfilesController) ProfileList(ec echo.Context) error {

  profile := []models.Profile{}

  c.T.Connection.DB().Find(&profile)

  if len(profile) <= 0 {

      reply := map[string]string{"Message": "No Profiles Found", "Code": "204"}

      return ec.JSON(http.StatusBadRequest, reply)
  }

  return ec.JSON(http.StatusOK, profile)
}

Now this was all working fine but I have now move on to building the frontend to this api. I am getting pq: sorry, too many clients already after about 96 or so requests.

So I run it though postman and got the same result. This is what I have done to correct the issue,

db := *c.T.Connection.DB()

db.Find(&profile)

defer db.Close()

Now that seems to work, I push over 500 requests though with postman and it worked fine. I am guest its the db.Close() that is helping there.

But I have read that the connection is a pool, so should the orginal code not work without needed a close on the connection? I thought that idle connections were released by the system over it was done with them? I have also read that due to it being a pool its not good to use db.Close().

So I am a little confused? Is what I done to fix the connection issue good? or is there a better way?

Many thanks.

You need to just create the one connection, and return the same instance:

type Database struct {
    T *Template
}

var db *gorm.DB

func init() {
    var err error
    db, err = gorm.Open("postgres", "host=localhost port=5010 user=postgres dbname=postgres password=password sslmode=disable")

    if err != nil {
         panic(err)
    }
}

func (admin *Database) DB() *gorm.DB {       
    return db
}