-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
278 lines (261 loc) · 8.91 KB
/
json.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright © 2015-2016 Erik Brady <brady@dvln.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The dvln/api/json.go module is for routines that might be useful
// for manipulating json beyond (or wrapping) the Go standard lib,
// also useful for "combining" JSON fields/data/errors from various
// packages that can then be dumped as a whole from anywhere.
package api
// for imports the goal is to use very little outside the std lib,
// note that str and cast have no dependencies outside the std lib
// (exception: cast testing file which uses 'testify')
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"github.com/dvln/cast"
"github.com/dvln/str"
)
var (
// Some default JSON output formatting settings that can be overridden
// via Set* API calls below (accessed under mutex from api.go)
jsonIndentLevel = 2
jsonPrefix = ""
jsonRaw = false
)
// JSONIndentLevel can be used to get the current indentation level for each
// "step" in PrettyJSON() output (defaults to 2 currently)
func JSONIndentLevel() int {
mu.RLock()
defer mu.RUnlock()
indentLevel := jsonIndentLevel
return indentLevel
}
// SetJSONIndentLevel can be used to change the indentation level for each
// "step" in pretty JSOn output being formatted via PrettyJSON()
func SetJSONIndentLevel(level int) {
mu.Lock()
defer mu.Unlock()
jsonIndentLevel = level
}
// JSONPrefix can be used to get the current prefix used for any JSON string
// being formatted via the PrettyJSON() routine
func JSONPrefix() string {
mu.RLock()
defer mu.RUnlock()
prefix := jsonPrefix
return prefix
}
// SetJSONPrefix can be used to change the string prefix for any JSON string
// being formatted via the PrettyJSON() routine.
func SetJSONPrefix(pfx string) {
mu.Lock()
defer mu.Unlock()
jsonPrefix = pfx
}
// JSONRaw can be used to determine if we're in raw JSON output mode (true)
// or not, true means the PrettyJSON() routine will do nothing
func JSONRaw() bool {
mu.RLock()
defer mu.RUnlock()
rawActive := jsonRaw
return rawActive
}
// SetJSONRaw can be used to change the raw JSON output mode so that
// the JSON is cleaned up and indented so it's human readable with various
// lines or if it's just "raw" and lumped together....if raw if false
// then other sections of this module use PrettyJSON to pretty it up.
func SetJSONRaw(b bool) {
mu.Lock()
defer mu.Unlock()
jsonRaw = b
}
// PrettyJSON pretty prints JSON data. Provide the data and that can be followed
// by two optional arguments, a prefix string and an indent level (both of which
// are strings). If neither is provided then no prefix used and indent of two
// spaces is the default (see cfgfile:jsonprefix, cfgfile:jsonindent and the
// related DVLN_JSONPREFIX, DVLN_JSONINDENT to adjust indentation and prefix
// as well as cfgfile:jsonraw and DVLN_JSONRAW for skipping pretty printing)
func PrettyJSON(b []byte, fmt ...string) (string, error) {
mu.RLock()
if jsonRaw {
mu.RUnlock()
// if there's an override to say pretty JSON is not desired, honor it,
// Feature: this could be changed to specifically remove carriage
// returns and shorten output around {} and :'s and such (?)
return cast.ToString(b), nil
}
prefix := jsonPrefix
indent := str.Pad("", " ", jsonIndentLevel)
mu.RUnlock()
if len(fmt) == 1 {
prefix = fmt[0]
} else if len(fmt) == 2 {
prefix = fmt[0]
indent = fmt[1]
}
var out bytes.Buffer
err := json.Indent(&out, b, prefix, indent)
return cast.ToString(out.Bytes()) + "\n", err
}
// EscapeJSONString escapes control chars in a string so JSON likes em
func EscapeJSONString(ctrl []byte) (esc []byte) {
u := []byte(`\u0000`)
for i, ch := range ctrl {
if ch <= 31 || ch == 34 {
if esc == nil {
esc = append(make([]byte, 0, len(ctrl)+len(u)), ctrl[:i]...)
}
esc = append(esc, u...)
hex.Encode(esc[len(esc)-2:], ctrl[i:i+1])
continue
}
if esc != nil {
esc = append(esc, ch)
}
}
if esc == nil {
return ctrl
}
return esc
}
// encodeMsginRawJSON takes the flavor of the Msg ("error", "warning" or "note")
// and the message and returns a JSON encoded string with no preceeding or
// following comments
func encodeMsgInRawJSON(flavor string, msg Msg) string {
if msg.Message == "" {
return ""
}
cleanMsg := EscapeJSONString([]byte(msg.Message))
rawJSON := fmt.Sprintf("\"%s\": { \"message\": \"%s\", \"code\": %d, \"level\": \"%s\"}", flavor, cleanMsg, msg.Code, msg.Level)
return rawJSON
}
// FatalJSONMsg is for cases where Marshal is failing so we need
// some JSON we can dump on the output... if we get to this level then
// what we're generating is a valid JSON error basically (shouldn't happen)
func FatalJSONMsg(apiVer string, errMsg Msg) string {
noteMsgJSON := encodeMsgInRawJSON("note", storedNote)
warnMsgJSON := encodeMsgInRawJSON("warning", storedNonFatalWarning)
errMsgJSON := encodeMsgInRawJSON("error", errMsg)
// we really need an error, try global setting else fallback to unknown
if errMsgJSON == "" {
errMsgJSON = encodeMsgInRawJSON("error", storedFatalError)
if errMsgJSON == "" {
errMsg = NewMsg("Unknown Fatal Error (Coding Error?)", 0, "UNKNOWN")
errMsgJSON = encodeMsgInRawJSON("error", errMsg)
}
}
msgsJSON := ""
if noteMsgJSON != "" {
msgsJSON = fmt.Sprintf("%s, ", noteMsgJSON)
}
if warnMsgJSON != "" {
msgsJSON = fmt.Sprintf("%s%s, ", msgsJSON, warnMsgJSON)
}
msgsJSON = fmt.Sprintf("%s%s", msgsJSON, errMsgJSON)
cmdError := -1
rawJSON := fmt.Sprintf("{ \"apiVersion\":\"%s\", \"id\": %d, %s }", apiVer, cmdError, msgsJSON)
output, err := PrettyJSON([]byte(rawJSON))
if err != nil {
output = rawJSON
}
return output
}
// GetJSONOutput takes the various things needed from a DVLN api call and
// combines pertinent details into a JSON "results" string (pretty or not
// depending upon settings) and returns that representation to the caller.
// It will return a boolean indicating if a fatal occurred (if so the err
// will be encoded in the JSON being returned already, print the string and
// exit non-zero basically if you get false back in the boolean)
func GetJSONOutput(apiVer string, context string, kind string, verbosity string, fields []string, items []interface{}) (string, bool) {
var j []byte
var err error
var output, rawJSON string
var errMsg, warnMsg, noteMsg Msg
fatalErr := false
if apiVer == "" {
// In case the API version couldn't be passed, last ditch try
apiVer = os.Getenv("PKG_API_APIVER")
if apiVer == "" {
apiVer = "?.?"
errMsg.Message = "No valid JSON API version is available"
errMsg.Code = 1001
errMsg.Level = "FATAL"
fatalErr = true
}
}
apiRoot := newAPIData(apiVer, context)
if errMsg.Message == "" && storedFatalError.Message != "" {
errMsg = storedFatalError
fatalErr = true
}
if storedNonFatalWarning.Message != "" {
warnMsg = storedNonFatalWarning
}
if storedNote.Message != "" {
noteMsg = storedNote
}
if errMsg.Message == "" {
// if no errors so far then add in our items and 'data' details
apiRoot.SetAPIItems(kind, verbosity, fields, items)
if warnMsg.Message != "" {
apiRoot.Warning = warnMsg
}
if noteMsg.Message != "" {
apiRoot.Note = noteMsg
}
} else {
// otherwise indicate issue and encode that into JSON
apiRoot.ID = -1
apiRoot.Error = errMsg
}
j, err = json.Marshal(apiRoot)
if err != nil {
if errMsg.Message == "" {
errMsg.Message = "Unable to marshal basic JSON API string"
errMsg.Code = 1002
errMsg.Level = "FATAL"
fatalErr = true
}
// hack: hard code some JSON and return an error... shouldn't happen
rawJSON = FatalJSONMsg(apiVer, errMsg)
return rawJSON, fatalErr
}
// put in indentation and formatting, can turn that off as well
// if desired via the "jsonraw" globs (viper) setting
output, err = PrettyJSON(j)
if err != nil {
warnMsg.Message = fmt.Sprintf("Unable to beautify JSON output: %s", err)
warnMsg.Code = 1003
warnMsg.Level = "ISSUE"
apiRoot.Warning = warnMsg
j, err = json.Marshal(apiRoot)
// if 1st marshal ok but pretty failed, add warning to JSON and if basic
// re-Marshal fails for any reason "bump" to a FATAL error, unlikely:
if err != nil {
// not a warning any more, scale it up to fatal error
warnMsg.Level = "FATAL"
fatalErr = true
rawJSON = FatalJSONMsg(apiVer, warnMsg)
return rawJSON, fatalErr
}
// retry pretty probably won't work again, if not just use raw json
output, err = PrettyJSON(j)
if err != nil {
output = cast.ToString(j)
}
}
// Return the output (typically), fatalErr is false if we get to here
return output, fatalErr
}