Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Database connection at each request. #1

Open
ByPikod opened this issue Sep 14, 2023 · 0 comments
Open

Database connection at each request. #1

ByPikod opened this issue Sep 14, 2023 · 0 comments

Comments

@ByPikod
Copy link

ByPikod commented Sep 14, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant