本文整理汇总了Golang中github.com/robertkrimen/otto.ToValue函数的典型用法代码示例。如果您正苦于以下问题:Golang ToValue函数的具体用法?Golang ToValue怎么用?Golang ToValue使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ToValue函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: javascriptReduceCount
func javascriptReduceCount(call otto.FunctionCall) otto.Value {
rere, err := call.Argument(2).ToBoolean()
if err != nil {
return ottoMust(otto.ToValue(fmt.Sprintf("Error getting rere flag: %v", err)))
}
ob, err := call.Argument(1).Export()
if err != nil {
return ottoMust(otto.ToValue(fmt.Sprintf("Error getting stuff: %v", err)))
}
l, ok := ob.([]interface{})
if !ok {
return ottoMust(otto.ToValue(fmt.Sprintf("unhandled %v/%T", ob, ob)))
}
if !rere {
return ottoMust(otto.ToValue(len(l)))
}
rv := float64(0)
for _, i := range l {
rv += zeroate(i)
}
return ottoMust(otto.ToValue(rv))
}
示例2: apiServiceCall
func apiServiceCall(call otto.FunctionCall) otto.Value {
svc := call.Argument(0).String()
interfaceValue, err := call.Argument(1).Export()
if err != nil {
logrus.Errorf("Plugins: rules: javascript supplied invalid parameters")
return otto.UndefinedValue()
}
params := interfaceValue.(map[string]interface{})
future := service.CallService(svc, params)
result := <-future.Result
var res otto.Value
if _, ok := result.(error); ok {
res, err = otto.ToValue(result.(error).Error())
} else {
res, err = otto.ToValue(result)
}
if err != nil {
logrus.Errorf("Plugins: rules: failed to convert service result to javascript")
return otto.UndefinedValue()
}
return res
}
示例3: javascriptReduceStats
func javascriptReduceStats(call otto.FunctionCall) otto.Value {
rere, err := call.Argument(2).ToBoolean()
if err != nil {
return ottoMust(otto.ToValue(fmt.Sprintf("Error getting rere flag: %v", err)))
}
ob, err := call.Argument(1).Export()
if err != nil {
return ottoMust(otto.ToValue(fmt.Sprintf("Error getting stuff: %v", err)))
}
l, ok := ob.([]interface{})
if !ok {
return ottoMust(otto.ToValue(fmt.Sprintf("unhandled %v/%T", ob, ob)))
}
rv := statsResult{}
if len(l) == 0 {
return rv.toOtto()
}
if rere {
// Rereduction goes here.
rv.load(l[0])
for i := 1; i < len(l); i++ {
ob := statsResult{}
ob.load(l[i])
rv.Add(ob)
}
return rv.toOtto()
}
// Initial reduction
rv.count = 1
rv.sum = zeroate(l[0])
rv.min = rv.sum
rv.max = rv.sum
rv.sumsqr = rv.sum * rv.sum
for i := 1; i < len(l); i++ {
v := zeroate(l[i])
rv.count++
rv.sum += v
rv.min = math.Min(rv.min, v)
rv.max = math.Max(rv.max, v)
rv.sumsqr += (v * v)
}
return rv.toOtto()
}
示例4: stringToValue
// stringToValue makes an otto.Value containing the specified string.
func stringToValue(message string) otto.Value {
val, err := otto.ToValue(message)
if err != nil {
return otto.UndefinedValue()
}
return val
}
示例5: main
func main() {
if len(os.Args) != 2 {
usage()
}
vm := motto.New()
vm.Set("fib", func(call otto.FunctionCall) otto.Value {
ret := fib(40)
v, _ := otto.ToValue(ret)
return v
})
vm.Set("XHR", func(call otto.FunctionCall) otto.Value {
return otto.UndefinedValue()
})
vm.Set("XHR.prototype.hello", func(call otto.FunctionCall) otto.Value {
return otto.UndefinedValue()
})
_, err := vm.Run(os.Args[1])
fmt.Printf("%v", err)
}
示例6: RunScript
func (rc *RunContext) RunScript(call otto.FunctionCall) otto.Value {
if len(call.ArgumentList) != 2 {
return rc.Err("RunScript must be (string, interface{}")
}
script, err := call.ArgumentList[0].ToString()
if err != nil {
log.Println(err.Error())
return rc.Err(err.Error())
}
parametersRaw := call.ArgumentList[1].String()
if err != nil {
log.Println(err.Error())
return rc.Err(err.Error())
}
parameters := map[string]interface{}{}
json.Unmarshal([]byte(parametersRaw), ¶meters)
result, err := rc.runner.RunScript(script, parameters, rc.db)
if err != nil {
log.Println(err.Error())
return rc.Err(err.Error())
}
resultJson, err := json.Marshal(result)
if err != nil {
log.Println(err.Error())
return rc.Err(err.Error())
}
r, err := otto.ToValue(string(resultJson))
if err != nil {
log.Println(err.Error())
return rc.Err(err.Error())
}
return r
}
示例7: Parse
// Parse parses the buffer and adds it to the line struct
// the config[otto.script] should be a javascript function which
// returns a hash. Each key in the hash will be added to the line Data
// and will be indexed
func (op *Parser) Parse(buffer []byte, line *ql.Line, config map[string]interface{}) error {
script := config["otto.script"].(string)
fn, err := op.o.Run(script)
if err != nil {
return err
}
this, err := otto.ToValue(nil)
if err != nil {
return err
}
result, err := fn.Call(this, string(buffer))
if err != nil {
return err
}
object := result.Object()
for _, key := range object.Keys() {
v, _ := object.Get(key)
if v.IsPrimitive() {
line.Data[key] = v.String()
}
}
return nil
}
示例8: _system_currentUser
//returns information about the system
func _system_currentUser(call otto.FunctionCall) otto.Value {
currentUser, err := user.Current()
if err != nil {
jsThrow(call, err)
}
objString := fmt.Sprintf(`
({
name: '%s',
homeDir: '%s',
uid: '%s',
gid: '%s',
username: '%s'
})
`, currentUser.Name, currentUser.HomeDir, currentUser.Uid, currentUser.Gid,
currentUser.Username)
obj, err := call.Otto.Object(objString)
if err != nil {
jsThrow(call, err)
}
v, err := otto.ToValue(obj)
if err != nil {
jsThrow(call, err)
}
return v
}
示例9: _file_eachLine
func _file_eachLine(call otto.FunctionCall) otto.Value {
if len(call.ArgumentList) != 2 {
jsThrow(call, errors.New("Wrong number of arguments."))
}
sourcePath, _ := call.Argument(0).ToString()
fn := call.Argument(1)
if !fileExists(sourcePath) {
jsThrow(call, errors.New("Source file doesn't exist"))
}
file, err := os.Open(sourcePath)
if err != nil {
jsThrow(call, err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line != "" {
v, _ := otto.ToValue(line)
fn.Call(v, v)
}
}
if err := scanner.Err(); err != nil {
jsThrow(call, err)
}
return otto.Value{}
}
示例10: throwJSException
// throwJSException panics on an otto.Value. The Otto VM will recover from the
// Go panic and throw msg as a JavaScript error.
func throwJSException(msg interface{}) otto.Value {
val, err := otto.ToValue(msg)
if err != nil {
glog.V(logger.Error).Infof("Failed to serialize JavaScript exception %v: %v", msg, err)
}
panic(val)
}
示例11: PrepareEnv
func (vm *RuleVM) PrepareEnv() error {
Service := func(call otto.FunctionCall) otto.Value {
svc := call.Argument(0).String()
interfaceValue, err := call.Argument(1).Export()
if err != nil {
logrus.Errorf("Plugins: rules: javascript supplied invalid parameters")
return otto.UndefinedValue()
}
params := interfaceValue.(map[string]interface{})
future := service.CallService(svc, params)
result := <-future.Result
var res otto.Value
if _, ok := result.(error); ok {
res, err = otto.ToValue(result.(error).Error())
} else {
res, err = otto.ToValue(result)
}
if err != nil {
logrus.Errorf("Plugins: rules: failed to convert service result to javascript")
return otto.UndefinedValue()
}
return res
}
Log := func(call otto.FunctionCall) otto.Value {
logrus.Infof("Plugins: jsrule: %s Log: %s", vm.Name, call.Argument(0).String())
return otto.Value{}
}
err := vm.otto.Set("Service", Service)
if err != nil {
return err
}
err = vm.otto.Set("Log", Log)
if err != nil {
return err
}
return nil
}
示例12: BenchmarkJSON
func BenchmarkJSON(b *testing.B) {
v, _ := otto.ToValue("foo")
var r string
for n := 0; n < b.N; n++ {
r = JSON(v)
}
result = r
}
示例13: _file_tempFolder
func _file_tempFolder(call otto.FunctionCall) otto.Value {
d, err := ioutil.TempDir("", "conduit")
if err != nil {
jsThrow(call, err)
}
v, _ := otto.ToValue(d)
return v
}
示例14: SqlExec
func (rc *RunContext) SqlExec(call otto.FunctionCall) otto.Value {
if len(call.ArgumentList) < 2 {
return rc.Err("Sql query called with too few parameters")
}
sqlString, err := call.ArgumentList[0].ToString()
if err != nil {
return rc.Err(err.Error())
}
sqlArgumentsRaw, err := call.Argument(1).Export()
if err != nil {
return rc.Err(err.Error())
}
sqlArguments, ok := sqlArgumentsRaw.([]interface{})
if !ok {
return rc.Err("Sql query parameter 2 must be an array")
}
log.Printf("EXEC: %s %#v\n", sqlString, sqlArguments)
res, err := rc.db.Exec(sqlString, sqlArguments...)
if err != nil {
return rc.Err(err.Error())
}
id, err := res.LastInsertId()
if err == nil && id > 0 {
log.Printf("Insert ID: %d\n", id)
val, _ := otto.ToValue(id)
return val
}
affected, err := res.RowsAffected()
if err == nil {
log.Printf("Rows: %d\n", affected)
val, _ := otto.ToValue(affected)
return val
}
val, _ := otto.ToValue(nil)
return val
}
示例15: _file_tempFile
func _file_tempFile(call otto.FunctionCall) otto.Value {
f, err := ioutil.TempFile("", "conduit")
if err != nil {
jsThrow(call, err)
}
defer f.Close()
v, _ := otto.ToValue(f.Name())
return v
}