Skip to content

Instantly share code, notes, and snippets.

@CodebyOmar
Last active February 20, 2019 16:03
Show Gist options
  • Save CodebyOmar/817d00551b8bd0471850321067b0fa30 to your computer and use it in GitHub Desktop.
Save CodebyOmar/817d00551b8bd0471850321067b0fa30 to your computer and use it in GitHub Desktop.
Moving database connection to an init function
// some other code here

func init() {
	once.Do(func() {
		args := []string{
			"host=" + os.Getenv("DB_HOST"),
			"port=" + os.Getenv("DB_PORT"),
			"user=" + os.Getenv("DB_USER"),
			"dbname=" + os.Getenv("DB_NAME"),
			"password=" + os.Getenv("DB_PASSWORD"),
		}
		var err error
		db, err = gorm.Open("postgres", s.Join(args, " "))
		if err != nil {
			fmt.Printf("failed to connect to DB: %v", err.Error())
			panic(err.Error())
		}
	})
}

// ...more code here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment