53 lines
1.2 KiB
Go
Raw Normal View History

2023-10-05 18:08:44 +02:00
package db
import (
"bufio"
"database/sql"
"fmt"
"os"
"strings"
"syscall"
"github.com/go-sql-driver/mysql"
"golang.org/x/term"
)
func getCredentials() (string, string, error) {
fmt.Printf("DB Benutzer: ")
user, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return "", "", fmt.Errorf("getCredentials: bufio.NewReader(os.Stdin).ReadString('\n'): %v", err)
}
fmt.Printf("DB Passwort: ")
bytePass, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", "", fmt.Errorf("getCredentials: term.ReadPassword(int(syscall.Stdin)): %v", err)
}
fmt.Println()
pass := string(bytePass)
return strings.TrimSpace(user), strings.TrimSpace(pass), nil
}
func OpenDB(dbName string) (*sql.DB, error) {
var err error
cfg := mysql.NewConfig()
cfg.DBName = dbName
cfg.User, cfg.Passwd, err = getCredentials()
if err != nil {
return nil, fmt.Errorf("OpenDB: getCredentials(): %v\n", err)
}
db, err := sql.Open("mysql", cfg.FormatDSN())
if err != nil {
return nil, fmt.Errorf("newDB: sql.Open(\"mysql\", cfg.FormatDSN()): %v\n", err)
}
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("newDB: db.Ping(): %v\n", err)
}
return db, nil
}