Skip to content

Instantly share code, notes, and snippets.

@jpitchardu
Last active May 6, 2024 03:28
Show Gist options
  • Save jpitchardu/8af177978120e007272fa54e5ff067f1 to your computer and use it in GitHub Desktop.
Save jpitchardu/8af177978120e007272fa54e5ff067f1 to your computer and use it in GitHub Desktop.
Go Result type
func ConnectToDB() result.Result[sql.DB] {
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
return result.NewResult(sql.Open("postgres", psqlInfo)).Try(func(db *sql.DB) error {
return db.Ping()
}).IfOk(func() {
fmt.Println("Successfully connected to database!")
})
}
func ConnectToDB() (*sql.DB, error) {
psqlInfo := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)
db, err := sql.Open("postgres", psqlInfo)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
fmt.Println("Successfully connected to database!")
return db, err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment