-
Notifications
You must be signed in to change notification settings - Fork 0
/
serverctl.go
100 lines (86 loc) · 1.91 KB
/
serverctl.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
package whoson
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"sort"
"time"
"google.golang.org/grpc"
"github.com/olekukonko/tablewriter"
)
// ServerCtl hold information for server control.
type ServerCtl struct {
server string
dumpResp *WSDumpResponse
out io.Writer
}
// NewServerCtl return new ServerCtl struct pointer.
func NewServerCtl(server string) *ServerCtl {
return &ServerCtl{
server: server,
out: os.Stdout,
}
}
// Dump Set grpc repository to sc.dumpResp
func (sc *ServerCtl) Dump() error {
l, err := grpc.Dial(sc.server,
grpc.WithInsecure(),
grpc.WithBlock(),
grpc.WithTimeout(time.Duration(5*time.Second)))
if err != nil {
return err
}
defer l.Close()
client := NewSyncClient(l)
req := &WSDumpRequest{}
r, err := client.Dump(context.Background(), req)
if err != nil {
return err
}
sc.dumpResp = r
return nil
}
// SetWriter Set io.Writer to sc.out
func (sc *ServerCtl) SetWriter(o io.Writer) {
sc.out = o
}
// WriteJSON Output json with io.Writer
func (sc *ServerCtl) WriteJSON() error {
var buf bytes.Buffer
err := json.Indent(&buf, sc.dumpResp.Json, "", " ")
if err != nil {
return err
}
if buf.String() != "null" {
fmt.Fprint(sc.out, buf.String())
}
return nil
}
// WriteTable Output Table with io.Writer
func (sc *ServerCtl) WriteTable() error {
t := tablewriter.NewWriter(sc.out)
t.SetHeader([]string{"Expire", "IP", "Data"})
t.SetAutoFormatHeaders(false)
t.SetBorder(false)
var sd []*StoreData
err := json.Unmarshal(sc.dumpResp.Json, &sd)
if err != nil {
return err
}
sort.Slice(sd, func(i, j int) bool {
if sd[i].Expire.Unix() < sd[j].Expire.Unix() {
return true
}
return (sd[i].Expire.Unix() == sd[j].Expire.Unix()) && (sd[i].IP.String() < sd[j].IP.String())
})
if len(sd) > 0 {
for _, v := range sd {
t.Append([]string{v.Expire.Format("2006-01-02 15:04:05"), v.IP.String(), v.Data})
}
t.Render()
}
return nil
}