title: How to create a Postgres database using GORM
body: <p>This is primarily focused towards having setup() and teardown() methods for a test suite that I'm planning on writing that involves creation of a DB.</p>
  
  <p>I've figured out how to create a DB using GORM. However, I'm not sure if this is the best approach.</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "github.com/jinzhu/gorm"
      _ "github.com/jinzhu/gorm/dialects/postgres"
      "log"
  )
  
  func main() {
      db, err := gorm.Open("postgres", "host=127.0.0.1 port=5432 user=superuser dbname=postgres password='' sslmode=disable")
      capture(err)
      db = db.Exec("CREATE DATABASE test_db;")
      if db.Error != nil {
          fmt.Println("Unable to create DB test_db, attempting to connect assuming it exists...")
          db, err = gorm.Open("postgres", "host=127.0.0.1 port=5432 user=superuser dbname=test_db password='' sslmode=disable")
          if err != nil {
             fmt.Println("Unable to connect to test_db")
             capture(err)
          }
      }
      defer db.Close()
  }
  
  func capture(err error) {
      if err != nil {
          log.Fatalf("%s", err)
     }
  }
  </code></pre>
  
  <p>I'm connecting to the default <code>postgres</code> DB first, after which I'm creating a second test DB which I'm planning on using.</p>
  
  <p>Is this the best approach ? Or is there a way to connect to Postgres without having a pre-existing DB.</p>
  
  <p><em>NOTE</em>: I've already looked up answers where people have used SQL driver to connect to a DB using only the connection string <code>user:password@/</code>. That has not worked in my case.(like <a href="https://stackoverflow.com/questions/30235031/how-to-create-a-new-mysql-database-with-go-sql-driver">here</a>)</p>
  
  <p>I've alse tried a connection string without having a DB name, that results in the driver trying to connect to a DB with the same name as the user. Which fails since such a DB does not exist.</p>