forked from cert-lv/graphoscope
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
223 lines (184 loc) · 4.96 KB
/
response.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package main
import (
"bytes"
"encoding/csv"
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"github.com/olekukonko/tablewriter"
"github.com/yukithm/json2csv"
)
/*
* Structure that API returns as a search result
*/
type APIresponse struct {
// Graph relations data
Relations []map[string]interface{} `json:"relations,omitempty"`
// Statistics (like Top 10)
// when the amount of returned results exceeds the limit
Stats map[string]interface{} `json:"stats,omitempty"`
// Queries debug info in case user requests it
Debug map[string]interface{} `json:"debug,omitempty"`
// If some data source returns an error this message will be shown.
// Graph data or statistics will be returned as well
Error string `json:"error,omitempty"`
// Allow safe writing to the slice
sync.RWMutex
}
/*
* Send search results to the API user.
* Receives user's IP, name, output format and SQL query
*/
func (a *APIresponse) send(w http.ResponseWriter, ip, username, format, sql string) {
_, err := fmt.Fprint(w, a.format(format))
if err != nil {
log.Error().
Str("ip", ip).
Str("username", username).
Str("sql", sql).
Msg("Can't send an API response: " + err.Error())
}
}
/*
* Format search output data.
* Receives a requested format, JSON will be used by default
*/
func (a *APIresponse) format(f string) string {
// Validate the format value
if f != "" && f != "json" && f != "table" {
log.Error().Msg("Unexpected API response format requested: '" + f + "', JSON used instead")
a.Error = "Unexpected API response format: '" + f + "', JSON used instead. " + a.Error
}
// Format the content if necessary
if f == "table" {
output := ""
if a.Error != "" {
output += "Error: " + a.Error + "\n"
if len(a.Stats) != 0 || len(a.Relations) != 0 {
output += "\n"
}
}
if len(a.Stats) != 0 {
output += "\"" + a.Stats["source"].(string) + "\" has too many results. "
csv, err := formatTo(a.Stats, "table")
if err != nil {
output += "Error: " + err.Error()
} else {
output += "Stats based on limited data:\n\n" + csv
}
}
if len(a.Relations) != 0 {
csv, err := formatTo(a.Relations, "table")
if err != nil {
output += "Error: " + err.Error()
} else {
if len(a.Stats) != 0 {
output += "\n\n"
}
output += csv
}
}
if a.Debug != nil {
if len(a.Relations) != 0 {
output += "\n\nDebug info:\n"
}
for source, section := range a.Debug {
if len(section.(map[string]interface{})) == 0 {
continue
}
csv, err := formatTo(section, "table")
if err != nil {
output += "Error: " + err.Error()
} else {
output += "\n" + source + "\n" + csv
}
}
}
return output
}
// Return JSON by default
output, err := formatTo(a, "json")
if err != nil {
return `{"error":"` + err.Error() + `"}`
}
return output
}
/*
* Format the given single object
*/
func formatTo(data interface{}, format string) (string, error) {
if format == "table" {
// JSON to CSV
// to get all the existing headers
csvSTR, err := json2csv.JSON2CSV(data)
if err != nil {
return "", fmt.Errorf("Can't convert API response to CSV: " + err.Error())
}
output := ""
buf := bytes.NewBufferString(output)
wr := json2csv.NewCSVWriter(buf)
wr.HeaderStyle = json2csv.DotNotationStyle
err = wr.WriteCSV(csvSTR)
if err != nil {
return "", fmt.Errorf("Can't format API response to CSV: " + err.Error())
}
// Read csv values using csv.Reader.
// Strings splitting by \n and "," is not enough as some fields
// may contain them
csvReader := csv.NewReader(strings.NewReader(buf.String()))
rows, err := csvReader.ReadAll()
if err != nil {
return "", fmt.Errorf("Can't parse CSV: " + err.Error())
}
// Find system internal fields to be removed.
// rows[0] is a headers row
fromSearch := -1
toSearch := -1
for i, header := range rows[0] {
if header == "from.search" {
fromSearch = i
}
if header == "to.search" {
toSearch = i
}
}
// Switch indexes in case 'To' element
// comes before the 'From' element,
// so the fields removing function works in the expected way
if toSearch < fromSearch {
i := toSearch
toSearch = fromSearch
fromSearch = i
}
rows[0] = removeFields(rows[0], fromSearch, toSearch)
// Clear CSV data from buffer to render a table
buf.Reset()
table := tablewriter.NewWriter(buf)
table.SetHeader(rows[0])
for i := 1; i < len(rows); i++ {
row := rows[i]
row = removeFields(row, fromSearch, toSearch)
table.Append(row)
}
table.Render()
return buf.String(), nil
}
// Return JSON by default
b, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf("Can't format API response to JSON: " + err.Error())
}
return string(b) + "\n", nil
}
/*
* Remove system internal fields from an output formatted as table
*/
func removeFields(slice []string, f, t int) []string {
if f == -1 && t == -1 {
return slice
}
slice = append(slice[:f], slice[f+1:]...)
return append(slice[:t-1], slice[t:]...)
}