/
table.go
53 lines (44 loc) · 1.02 KB
/
table.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
package table
import (
"fmt"
"os"
"reflect"
"github.com/olekukonko/tablewriter"
)
// PrintStruct prints a table of the given struct
func PrintStruct(in interface{}, tags ...string) {
if in == nil {
return
}
rows := rows(in, tags...)
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader(append([]string{"Name", "Value"}, tags...))
table.SetAlignment(tablewriter.ALIGN_LEFT)
for _, v := range rows {
table.Append(v)
}
table.Render() // Send output
}
// rows returns a slice of strings representing the struct fields
func rows(v interface{}, tags ...string) [][]string {
t := reflect.TypeOf(v).Elem()
r := reflect.ValueOf(v)
rows := make([][]string, 0)
for i := 0; i < t.NumField(); i++ {
row := make([]string, 0)
field := t.Field(i)
if !field.IsExported() {
continue
}
row = append(row,
field.Name,
fmt.Sprint(reflect.Indirect(r).FieldByName(field.Name)),
)
for _, v := range tags {
column := field.Tag.Get(v)
row = append(row, column)
}
rows = append(rows, row)
}
return rows
}