forked from stretchr/ottox
/
files.go
81 lines (70 loc) · 2.23 KB
/
files.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
package ottox
import (
"github.com/robertkrimen/otto"
"io"
"os"
)
// RegisterMethodFileOpen registers a method that is capable of opening files.
//
// Response object:
//
// {
// ok: true|false,
// reader: "readFile" // the method to use to read from the file
// }
//
// To read the entire file into a variable:
//
// // in Go...
// RegisterMethodFileOpen(js, "openFile")
//
// // in the script...
// var file = openFile("filename"); // open the file
// var read = eval(file.reader); // get the reader method
// var close = eval(file.closer); // get the closer method
//
// var fileContents = read(-1); // read everything
// close(); // close the file
//
func RegisterMethodFileOpen(runtime *otto.Otto, methodName string) error {
runtime.Set(methodName, func(call otto.FunctionCall) otto.Value {
// check the arguments
if len(call.ArgumentList) != 1 {
raiseError(runtime, "%s takes 1 arguments: %s(filename)", methodName, methodName)
return otto.UndefinedValue()
}
// get the arguments
var filename string
var err error
if filename, err = call.Argument(0).ToString(); err != nil {
raiseError(runtime, "%s first argument must be a string containing the filename", methodName)
return otto.UndefinedValue()
}
// open the file
var file io.ReadCloser
if file, err = os.Open(filename); err != nil {
raiseError(runtime, "Failed to open file '%s': %s", filename, err)
return otto.UndefinedValue()
}
// add the reader
var readerMethodName string = generateMethodName("fileRead")
NewReader(runtime, readerMethodName, file)
// add the closer
var closerMethodName string = generateMethodName("fileClose")
runtime.Set(closerMethodName, func(call otto.FunctionCall) otto.Value {
if err := file.Close(); err != nil {
raiseError(runtime, "Failed to close file '%s': %s", filename, err)
return otto.FalseValue()
}
return otto.TrueValue()
})
var response otto.Value
if response, err = makeMap(runtime, map[string]interface{}{"reader": readerMethodName, "closer": closerMethodName, "ok": true}); err != nil {
raiseError(runtime, "%s failed to make response map.", methodName)
return otto.UndefinedValue()
}
// done
return response
})
return nil
}