-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatter.go
109 lines (86 loc) · 1.88 KB
/
formatter.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
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"fmt"
"github.com/hfern/goseq"
)
type FieldSpec struct {
name string
length int
}
type SvResponse struct {
err error
server goseq.Server
info goseq.ServerInfo
}
type Printer interface {
Init(fields []FieldSpec, in <-chan SvResponse)
Run() // calls with go Run()
Done()
}
type textWriter struct {
fields []FieldSpec
in <-chan SvResponse
}
func (w *textWriter) Init(fields []FieldSpec, in <-chan SvResponse) {
w.fields = fields
w.in = in
}
func (w *textWriter) Run() {
for sv := range w.in {
for i, field := range w.fields {
if i > 0 {
fmt.Print(masterOptions.Divider)
}
var val interface{}
if handler, ok := serverMethodAccessors[field.name]; ok {
val = handler(sv.info)
}
if handler, ok := serverProperties[field.name]; ok {
val = handler(sv.server)
}
if transformer, ok := serverFieldTransformers[field.name]; ok {
val = transformer(val)
}
written, _ := fmt.Print(val)
for ; written < field.length; written++ {
fmt.Print(" ")
}
}
fmt.Print("\n")
}
}
func (w *textWriter) Done() {}
type jsonWriter struct {
fields []FieldSpec
in <-chan SvResponse
servers []map[string]Any
}
func (w *jsonWriter) Init(fields []FieldSpec, in <-chan SvResponse) {
w.fields = fields
w.in = in
w.servers = make([]map[string]Any, 0)
}
func (w *jsonWriter) Run() {
for sv := range w.in {
svEntry := make(map[string]Any, len(w.fields))
for _, field := range w.fields {
var val interface{}
if handler, ok := serverMethodAccessors[field.name]; ok {
val = handler(sv.info)
}
if handler, ok := serverProperties[field.name]; ok {
val = handler(sv.server)
}
svEntry[field.name] = val
}
w.servers = append(w.servers, svEntry)
}
}
func (w *jsonWriter) Done() {
text, err := json.Marshal(w.servers)
if err != nil {
panic(err)
}
fmt.Print(string(text))
}