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
101
| package mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"io"
"log"
"os"
"text/tabwriter"
"text/template"
)
// Mysql 连接配置
var (
dbUser = "root"
dbPass = "Secret123."
dbName = "test_db"
)
// ErrHandle Mysql错误处理
func ErrHandle(err error, pos string, v ...interface{}) {
format := "%s, %s";
if v != nil {
for range v {
format = format + ", %s"
}
log.Panicf(format+"\n", pos, err, v)
} else {
log.Panicf(format+"\n", pos, err)
}
}
// dsn string
func dsn() string {
return fmt.Sprintf("%s:%s@/%s", dbUser, dbPass, dbName)
}
// GetDb 获取DB实例
func GetDb() (db *sql.DB, err error) {
db, err = sql.Open("mysql", dsn())
if err != nil {
ErrHandle(err, "sql.open")
}
if err = db.Ping(); err != nil {
ErrHandle(err, "sql.ping")
}
return
}
// ShowStatus 打印当前连接DB状态信息
func ShowStatus(db *sql.DB) {
status := db.Stats()
stData := map[string]interface{}{
"MaxOpenConnections": status.MaxOpenConnections,
"OpenConnections": status.OpenConnections,
"InUse": status.InUse,
"Idle": status.Idle,
"WaitCount": status.WaitCount,
"WaitDuration": status.WaitDuration,
"MaxIdleClosed": status.MaxIdleClosed,
"MaxLifetimeClosed": status.MaxLifetimeClosed,
}
// text/tabwriter
textTableShow(os.Stdout, stData)
// text/template
// textTmplShow(os.Stdout, stData)
}
// 表格输出
func textTableShow(w io.Writer, data map[string]interface{}) {
const format = "%v\t%v\n"
tw := new(tabwriter.Writer).Init(w, 0, 8, 2, ' ', 0)
fmt.Fprintf(tw, format, "db.Stats Key", "Values")
fmt.Fprintf(tw, format, "----------", "-----")
for k, v := range data {
fmt.Fprintf(tw, format, k, v)
}
_ = tw.Flush()
}
// 文本模板输出
func textTmplShow(w io.Writer, data map[string]interface{}) {
// tmpl
const tmplTxt = `DB STATUS
-----------------------{{range $k, $v := .}}
{{printf "%-18v" $k}} => {{printf "%v" .}}{{end}}
`
tmpl, err := template.New("showStatus").Parse(tmplTxt)
if err != nil {
ErrHandle(err, "template.Parse")
}
if err := tmpl.Execute(w, data); err != nil {
ErrHandle(err, "template.Execute")
}
}
|