forked from xyproto/algernon
/
jnode.go
423 lines (369 loc) · 10 KB
/
jnode.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package main
import (
"bytes"
"encoding/json"
"io/ioutil"
"net/http" // For sending JSON requests
"strings"
log "github.com/sirupsen/logrus"
"github.com/xyproto/jpath"
"github.com/yuin/gopher-lua"
)
// For dealing with JSON documents and strings
const (
// Identifier for the JNode class in Lua
lJNodeClass = "JNode"
// Prefix when indenting JSON
indentPrefix = ""
)
// Get the first argument, "self", and cast it from userdata to a library (which is really a hash map).
func checkJNode(L *lua.LState) *jpath.Node {
ud := L.CheckUserData(1)
if jnode, ok := ud.Value.(*jpath.Node); ok {
return jnode
}
L.ArgError(1, "JSON node expected")
return nil
}
// Takes a JNode, a JSON path (optional) and JSON data.
// Stores the JSON data. Returns true if successful.
func jnodeAdd(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
top := L.GetTop()
jsonpath := "x"
jsondata := ""
if top == 2 {
jsondata = L.ToString(2)
if jsondata == "" {
L.ArgError(2, "JSON data expected")
}
} else if top == 3 {
jsonpath = L.ToString(2)
// Check for { to help avoid allowing JSON data as a JSON path
if jsonpath == "" || strings.Contains(jsonpath, "{") {
L.ArgError(2, "JSON path expected")
}
jsondata = L.ToString(3)
if jsondata == "" {
L.ArgError(3, "JSON data expected")
}
}
err := jnode.AddJSON(jsonpath, []byte(jsondata))
if err != nil {
if top == 2 || strings.HasPrefix(err.Error(), "invalid character") {
log.Error("JSON data: ", err)
} else {
log.Error(err)
}
}
L.Push(lua.LBool(err == nil))
return 1 // number of results
}
// Takes a JNode and a JSON path.
// Returns a value or an empty string.
func jnodeGetNode(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
jsonpath := L.ToString(2)
if jsonpath == "" {
L.ArgError(2, "JSON path expected")
}
node := jnode.GetNode(jsonpath)
ud := L.NewUserData()
ud.Value = node
L.SetMetatable(ud, L.GetTypeMetatable(lJNodeClass))
L.Push(ud)
return 1 // number of results
}
// Takes a JNode and a JSON path.
// Returns a value or an empty string.
func jnodeGetString(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
jsonpath := L.ToString(2)
if jsonpath == "" {
L.ArgError(2, "JSON path expected")
}
node := jnode.GetNode(jsonpath)
L.Push(lua.LString(node.String()))
return 1 // number of results
}
// Take a JNode, a JSON path and a string.
// Returns nothing
func jnodeSet(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
jsonpath := L.ToString(2)
if jsonpath == "" {
L.ArgError(2, "JSON path expected")
}
sval := L.ToString(3)
if sval == "" {
L.ArgError(3, "String value expected")
}
jnode.Set(jsonpath, sval)
return 0 // number of results
}
// Take a JNode and a JSON path.
// Remove a key from a map. Return true if successful.
func jnodeDelKey(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
jsonpath := L.ToString(2)
if jsonpath == "" {
L.ArgError(2, "JSON path expected")
}
err := jnode.DelKey(jsonpath)
if err != nil {
log.Error(err)
}
L.Push(lua.LBool(nil == err))
return 1 // number of results
}
// Given a JNode, return the JSON document.
// May return an empty string.
func jnodeJSON(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
data, err := jnode.PrettyJSON()
retval := ""
if err == nil { // ok
retval = string(data)
}
L.Push(lua.LString(retval))
return 1 // number of results
}
// Given a JNode, return the JSON document.
// May return an empty string.
// Not prettily formatted.
func jnodeJSONcompact(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
data, err := jnode.JSON()
retval := ""
if err == nil { // ok
retval = string(data)
}
L.Push(lua.LString(retval))
return 1 // number of results
}
// Send JSON to host. First argument: URL
// Second argument (optional) Auth token.
// Returns a string that starts with FAIL if it fails.
// Returns the HTTP status code if it works out.
func jnodePOSTToURL(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
posturl := L.ToString(2)
if posturl == "" {
L.ArgError(2, "URL for sending a JSON POST requests to expected")
}
if !strings.HasPrefix(posturl, "http") {
L.ArgError(2, "URL must start with http or https")
}
top := L.GetTop()
authtoken := ""
if top == 3 {
// Optional
authtoken = L.ToString(3)
}
// Render JSON
jsonData, err := jnode.JSON()
if err != nil {
L.Push(lua.LString("FAIL: " + err.Error()))
return 1 // number of results
}
// Set up request
client := &http.Client{}
req, err := http.NewRequest("POST", posturl, bytes.NewReader(jsonData))
if err != nil {
log.Error(err)
return 0 // number of results
}
if authtoken != "" {
req.Header.Add("Authorization", "auth_token=\""+authtoken+"\"")
}
req.Header.Add("Content-Type", "application/json; charset=utf-8")
// Send request and return result
resp, err := client.Do(req)
if err != nil {
log.Error(err)
return 0 // number of results
}
L.Push(lua.LString(resp.Status))
return 1 // number of results
}
// Send JSON to host. First argument: URL
// Second argument (optional) Auth token.
// Returns a string that starts with FAIL if it fails.
// Returns the HTTP status code if it works out.
func jnodePUTToURL(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
puturl := L.ToString(2)
if puturl == "" {
L.ArgError(2, "URL for sending a JSON PUT requests to expected")
}
if !strings.HasPrefix(puturl, "http") {
L.ArgError(2, "URL must start with http or https")
}
top := L.GetTop()
authtoken := ""
if top == 3 {
// Optional
authtoken = L.ToString(3)
}
// Render JSON
jsonData, err := jnode.JSON()
if err != nil {
L.Push(lua.LString("FAIL: " + err.Error()))
return 1 // number of results
}
// Set up request
client := &http.Client{}
req, err := http.NewRequest("PUT", puturl, bytes.NewReader(jsonData))
if err != nil {
log.Error(err)
return 0 // number of results
}
if authtoken != "" {
req.Header.Add("Authorization", "auth_token=\""+authtoken+"\"")
}
req.Header.Add("Content-Type", "application/json; charset=utf-8")
// Send request and return result
resp, err := client.Do(req)
if err != nil {
log.Error(err)
return 0 // number of results
}
L.Push(lua.LString(resp.Status))
return 1 // number of results
}
// Receive JSON from host. First argument: URL
// Returns a string that starts with FAIL if it fails.
// Fills the current JSON node if it works out.
func jnodeGETFromURL(L *lua.LState) int {
jnode := checkJNode(L) // arg 1
posturl := L.ToString(2)
if posturl == "" {
L.ArgError(2, "URL for sending a JSON POST requests to expected")
}
if !strings.HasPrefix(posturl, "http") {
L.ArgError(2, "URL must start with http or https")
}
// Send request
resp, err := http.Get(posturl)
if err != nil {
log.Error(err.Error())
return 0 // number of results
}
if resp.Status != "200 OK" {
L.Push(lua.LString(resp.Status))
return 1 // number of results
}
bodyData, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
log.Error(err)
return 0 // number of results
}
newJnode, err := jpath.New(bodyData)
if err != nil {
log.Error(err)
return 0 // number of results
}
*jnode = *newJnode
L.Push(lua.LString(resp.Status))
return 1 // number of results
}
// Create a new JSON node. JSON data as the first argument is optional.
// Logs an error if the given JSON can't be parsed.
// Always returns a JSON Node.
func constructJNode(L *lua.LState) (*lua.LUserData, error) {
// Create a new JNode
var jnode *jpath.Node
top := L.GetTop()
if top == 1 {
// Optional
jsondata := []byte(L.ToString(1))
var err error
jnode, err = jpath.New(jsondata)
if err != nil {
log.Error(err)
jnode = jpath.NewNode()
}
} else {
jnode = jpath.NewNode()
}
// Create a new userdata struct
ud := L.NewUserData()
ud.Value = jnode
L.SetMetatable(ud, L.GetTypeMetatable(lJNodeClass))
return ud, nil
}
// The hash map methods that are to be registered
var jnodeMethods = map[string]lua.LGFunction{
"__tostring": jnodeJSON,
"add": jnodeAdd,
"get": jnodeGetNode,
"getstring": jnodeGetString,
"set": jnodeSet,
"delkey": jnodeDelKey,
"pretty": jnodeJSON,
"compact": jnodeJSONcompact,
"send": jnodePOSTToURL,
"POST": jnodePOSTToURL,
"PUT": jnodePUTToURL,
"receive": jnodeGETFromURL,
"GET": jnodeGETFromURL,
}
// Make functions related JSON nodes
func exportJNode(L *lua.LState) {
// Register the JNode class and the methods that belongs with it.
mt := L.NewTypeMetatable(lJNodeClass)
mt.RawSetH(lua.LString("__index"), mt)
L.SetFuncs(mt, jnodeMethods)
// The constructor for new Libraries takes only an optional id
L.SetGlobal("JNode", L.NewFunction(func(L *lua.LState) int {
// Construct a new JNode
userdata, err := constructJNode(L)
if err != nil {
log.Error(err)
L.Push(lua.LString(err.Error()))
return 1 // Number of returned values
}
// Return the Lua JNode object
L.Push(userdata)
return 1 // number of results
}))
}
func exportJSONFunctions(L *lua.LState) {
// Lua function for converting a table to JSON (string or int)
toJSON := L.NewFunction(func(L *lua.LState) int {
var (
b []byte
err error
)
table := L.ToTable(1)
//
// NOTE:
// JSON keys in maps are always strings!
// See: https://stackoverflow.com/questions/24284612/failed-to-json-marshal-map-with-non-string-keys
//
// Convert the Lua table to a map that can be used when converting to JSON (map[string]interface{})
mapinterface := table2interfacemap(table)
// If an optional argument is supplied, indent the given number of spaces
if L.GetTop() == 2 {
indentLevel := L.ToInt(2)
indentString := ""
for i := 0; i < indentLevel; i++ {
indentString += " "
}
b, err = json.MarshalIndent(mapinterface, indentPrefix, indentString)
} else {
b, err = json.Marshal(mapinterface)
}
if err != nil {
log.Error(err)
return 0 // number of results
}
L.Push(lua.LString(string(b)))
return 1 // number of results
})
// Convert a table to JSON
L.SetGlobal("JSON", toJSON)
L.SetGlobal("toJSON", toJSON) // Alias for backward compatibility
L.SetGlobal("ToJSON", toJSON) // Alias for backward compatibility
}