-
Notifications
You must be signed in to change notification settings - Fork 9
/
display.go
56 lines (47 loc) · 972 Bytes
/
display.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
package main
import (
"database/sql"
"fmt"
"os"
"strings"
"text/tabwriter"
)
func DisplayResults(rows *sql.Rows) error {
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return err
}
var (
w = tabwriter.NewWriter(os.Stdout, 10, 1, 3, ' ', 0)
num = len(columns)
format = fmt.Sprintf("%s\n", getNumTabs(num))
values = make([]interface{}, num)
strs = make([]string, num)
)
for i := 0; i < num; i++ {
values[i] = &strs[i]
}
fmt.Fprintf(w, format, toInterface(columns)...)
for rows.Next() {
if err := rows.Scan(values...); err != nil {
return err
}
fmt.Fprintf(w, format, toInterface(strs)...)
}
return w.Flush()
}
func getNumTabs(num int) string {
tabs := []string{}
for i := 0; i < num; i++ {
tabs = append(tabs, "%s\t")
}
return strings.Join(tabs, "")
}
func toInterface(strs []string) []interface{} {
out := []interface{}{}
for _, s := range strs {
out = append(out, s)
}
return out
}