forked from LunaNode/lobster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
61 lines (52 loc) · 1.36 KB
/
database.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
package lobster
import _ "github.com/go-sql-driver/mysql"
import "database/sql"
import "log"
import "net/http"
type Database struct {
db *sql.DB
}
func GetDatabaseString() string {
s := cfg.Database.Username + ":" + cfg.Database.Password + "@"
if cfg.Database.Host != "localhost" {
s += cfg.Database.Host
}
s += "/" + cfg.Database.Name + "?charset=utf8&parseTime=true"
return s
}
func MakeDatabase() *Database {
this := new(Database)
db, err := sql.Open("mysql", GetDatabaseString())
checkErr(err)
this.db = db
return this
}
func (this *Database) Query(q string, args ...interface{}) *sql.Rows {
if cfg.Default.Debug {
log.Printf("%s on %v", q, args)
}
rows, err := this.db.Query(q, args...)
checkErr(err)
return rows
}
func (this *Database) QueryRow(q string, args ...interface{}) *sql.Row {
if cfg.Default.Debug {
log.Printf("%s on %v", q, args)
}
row := this.db.QueryRow(q, args...)
return row
}
func (this *Database) Exec(q string, args ...interface{}) sql.Result {
if cfg.Default.Debug {
log.Printf("%s on %v", q, args)
}
result, err := this.db.Exec(q, args...)
checkErr(err)
return result
}
func (this *Database) WrapHandler(handler func(http.ResponseWriter, *http.Request, *Database)) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
defer errorHandler(w, r, true)
handler(w, r, this)
}
}