Skip to content

Commit 348986c

Browse files
authored
Merge pull request #175 from edanp/master
Add readFile to JS runtime
2 parents 496ebed + 39c0af7 commit 348986c

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,8 @@ dumbproxy can select upstream proxy dynamically invoking `getProxy` JS function
360360

361361
Note that this option can be repeated multiple times, same as `-proxy` option for chaining of proxies. These two options can be used together and order of chaining will be as they come in command line. For generalization purposes we can say that `-proxy` option is equivalent to `-js-proxy-router` option with script which returns just one static proxy.
362362

363+
`getProxy` scripts can read helper files using the built-in `readFile(path)` function that returns the file contents as a string.
364+
363365
`getProxy` function is invoked with the [same parameters](#access-filter-by-js-script) as the `access` function. But unlike `access` function it is expected to return proxy URL in string format *scheme://[user:password@]host:port* or empty string `""` if no additional upstream proxy needed (i.e. direct connection if there are no other proxy dialers defined in chain). See [supported upstream proxy schemes](#supported-upstream-proxy-schemes) for details.
364366

365367
Example:

dialer/jsrouter.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ func NewJSRouter(filename string, instances int, factory func(string) (Dialer, e
3737
if err != nil {
3838
return nil, errors.New("can't add print function to runtime")
3939
}
40+
err = jsext.AddFileReader(vm)
41+
if err != nil {
42+
return nil, errors.New("can't add file reader function to runtime")
43+
}
4044
vm.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
4145
_, err = vm.RunString(string(script))
4246
if err != nil {

jsext/filereader.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package jsext
2+
3+
import (
4+
"os"
5+
6+
"github.com/dop251/goja"
7+
)
8+
9+
func AddFileReader(vm *goja.Runtime) error {
10+
return vm.Set("readFile", func(call goja.FunctionCall) goja.Value {
11+
if len(call.Arguments) != 1 {
12+
panic(vm.NewTypeError("readFile expects exactly 1 argument"))
13+
}
14+
15+
filename := call.Argument(0).String()
16+
content, err := os.ReadFile(filename)
17+
if err != nil {
18+
panic(vm.NewGoError(err))
19+
}
20+
21+
return vm.ToValue(string(content))
22+
})
23+
}

0 commit comments

Comments
 (0)