41 lines
612 B
Go
41 lines
612 B
Go
|
package database
|
||
|
|
||
|
import (
|
||
|
"database/sql"
|
||
|
"encoding/json"
|
||
|
"log"
|
||
|
"os"
|
||
|
|
||
|
"github.com/go-sql-driver/mysql"
|
||
|
)
|
||
|
|
||
|
func readConfigFromFile(filename string) mysql.Config {
|
||
|
bytes, err := os.ReadFile(filename)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
var config mysql.Config
|
||
|
err = json.Unmarshal(bytes, &config)
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
return config
|
||
|
}
|
||
|
|
||
|
func GetDatabaseFromConfig(filename string) *sql.DB {
|
||
|
config := readConfigFromFile(filename)
|
||
|
|
||
|
db, err := sql.Open("mysql", config.FormatDSN())
|
||
|
|
||
|
if err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
if err = db.Ping(); err != nil {
|
||
|
log.Fatal(err)
|
||
|
}
|
||
|
|
||
|
return db
|
||
|
}
|