-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
100 lines (76 loc) · 1.69 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"database/sql"
"fmt"
"os"
)
func getEnv(envKey string) (envValue string, err error) {
envValue, ok := os.LookupEnv(envKey)
if ok != true {
err = fmt.Errorf("please set %s environment variable", envKey)
return
}
return envValue, nil
}
func dbConnection() (*sql.DB, error) {
username, err := getEnv("MYSQL_USERNAME")
if err != nil {
return nil, err
}
password, err := getEnv("MYSQL_PASSWORD")
if err != nil {
return nil, err
}
host, err := getEnv("MYSQL_HOST")
if err != nil {
return nil, err
}
database, err := getEnv("MYSQL_DATABASE")
if err != nil {
return nil, err
}
connection := fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8", username, password, host, database)
// Open and connect do DB
db, err := sql.Open("mysql", connection)
if err != nil {
return nil, err
}
// Open doesn't open a connection. Validate DSN data:
err = db.Ping()
if err != nil {
return nil, err
}
return db, nil
}
func getSongsFromDB(db *sql.DB) ([]SongDetails, error) {
var l []SongDetails
tx, err := db.Begin()
if err != nil {
return nil, err
}
defer func() {
switch err {
case nil:
err = tx.Commit()
default:
tx.Rollback()
}
}()
rows, err := db.Query("SELECT id, filename, artist, title, album, lenght, share, url, image, playlist FROM details ORDER BY id DESC")
if err != nil {
return nil, err
}
for rows.Next() {
var s SongDetails
rows.Scan(&s.ID, &s.Filename, &s.Artist, &s.Title, &s.Album, &s.Length, &s.Share, &s.URL, &s.Image, &s.Playlist)
l = append(l, s)
}
defer rows.Close()
return l, nil
}
func doesExist(filename string) bool {
if _, err := os.Stat(filename); os.IsNotExist(err) {
return false
}
return true
}