Last active
May 6, 2024 03:28
-
-
Save jpitchardu/8af177978120e007272fa54e5ff067f1 to your computer and use it in GitHub Desktop.
Go Result type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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