-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverjsonview.go
110 lines (89 loc) · 2.08 KB
/
serverjsonview.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
110
package main
import (
"encoding/json"
"fmt"
)
type jsonResponseWrapper struct {
Servers []interface{}
}
func viewServerJSON(options *ServerQueryOptions, servers []ServerAttrPair) {
formattedServers := make([]interface{}, len(servers))
for i, server := range servers {
formattedServers[i] = jsonFormatServer(server, options)
}
wrapper := jsonResponseWrapper{Servers: formattedServers}
encoded, err := json.Marshal(wrapper)
if err != nil {
panic(err)
}
fmt.Print(string(encoded))
}
func jsonFormatServer(server ServerAttrPair, opts *ServerQueryOptions) interface{} {
return map[string]interface{}{
"Address": server.Attrs.Address,
"Players": jsonFormatPlayers(server.Attrs.Players, opts),
"Info": jsonFormatInfo(server.Attrs.Info, opts),
"Rules": jsonFormatRules(server.Attrs.Rules, opts),
}
}
func jsonFormatRules(rules MaybeRules, opts *ServerQueryOptions) interface{} {
if opts.NoRules {
return nil
}
ret := struct {
Error interface{}
Rules interface{}
}{}
if rules.Error != nil {
ret.Error = rules.Error.Error()
ret.Rules = nil
return ret
}
ret.Rules = make(map[string]interface{})
return ret
}
func jsonFormatInfo(info MaybeInfo, opts *ServerQueryOptions) interface{} {
if opts.NoInfo {
return nil
}
ret := struct {
Error interface{}
Info interface{}
}{
Error: nil,
Info: nil,
}
if info.Error == nil {
ret.Info = info.Info
} else {
ret.Error = info.Error.Error()
}
return ret
}
func jsonFormatPlayers(mbplys MaybePlayers, opts *ServerQueryOptions) interface{} {
players := mbplys.Players
if opts.NoPlayers {
return nil
}
fmtPlayers := make([]map[string]interface{}, len(players))
for i, player := range players {
ply := make(map[string]interface{})
ply["Index"] = player.Index()
ply["Name"] = player.Name()
ply["Duration"] = player.Duration()
ply["Score"] = player.Score()
fmtPlayers[i] = ply
}
type ReturnStruct struct {
Error interface{}
Players interface{}
}
ret := ReturnStruct{
Error: nil,
Players: fmtPlayers,
}
if mbplys.Error != nil {
ret.Error = mbplys.Error.Error()
}
return ret
}