Skip to content

Database connection at each request. #1

Open
@ByPikod

Description

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.

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions