diff --git a/db.go b/db.go new file mode 100644 index 0000000..3f0d155 --- /dev/null +++ b/db.go @@ -0,0 +1,52 @@ +package sicherheitsunterweisung + +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 +} diff --git a/go.mod b/go.mod index 159d227..729edcb 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,10 @@ module streifling.com/jason/sicherheitsunterweisung go 1.21.1 + +require ( + github.com/go-sql-driver/mysql v1.7.1 + golang.org/x/term v0.13.0 +) + +require golang.org/x/sys v0.13.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..009f59d --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +github.com/go-sql-driver/mysql v1.7.1 h1:lUIinVbN1DY0xBg0eMOzmmtGoHwWBbvnWubQUrtU8EI= +github.com/go-sql-driver/mysql v1.7.1/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI= +golang.org/x/sys v0.13.0 h1:Af8nKPmuFypiUBjVoU9V20FiaFXOcuZI21p0ycVYYGE= +golang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.13.0 h1:bb+I9cTfFazGW51MZqBVmZy7+JEJMouUHTUSKVQLBek= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= diff --git a/main.go b/main.go index d03651c..f0006f6 100644 --- a/main.go +++ b/main.go @@ -1,4 +1,4 @@ -package main +package sicherheitsunterweisung import ( "fmt" @@ -33,8 +33,13 @@ func main() { var i, j int64 var b Briefing - mux := http.NewServeMux() i, j = 1, 1 + mux := http.NewServeMux() + + db, err := OpenDB("sicherheitsunterweisung") + if err != nil { + log.Fatalln(err) + } mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {