example-golang icon indicating copy to clipboard operation
example-golang copied to clipboard

Database connection at each request.

Open ByPikod opened this issue 2 years ago • 0 comments

type Service struct {

}

func (m *Service) Db() *gorm.DB {
	return config.Db()
}

The code above adds a utility function to quickly access config.Db() But the function config.Db() creates a new connection each time with the code below:

func Db() *gorm.DB {
	dsn := fmt.Sprintf(
		"host=%s port=%s dbname=%s user=%s password=%s sslmode=disable TimeZone=%s",
		os.Getenv("DB_HOST"),
		os.Getenv("DB_PORT"),
		os.Getenv("DB_NAME"),
		os.Getenv("DB_USER"),
		os.Getenv("DB_PASSWORD"),
		os.Getenv("DB_TIMEZONE"),
	)

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect database")
	}

	return db
}

That means each request to the HTTP server will re-create the database connection. I wonder if this is something you made on purpose or you missed this point. I am a newbie at go-lang so I'd like to know.

Thanks for this inspiring project.

ByPikod avatar Sep 14 '23 08:09 ByPikod