本文整理汇总了Golang中github.com/robertkrimen/otto.Value类的典型用法代码示例。如果您正苦于以下问题:Golang Value类的具体用法?Golang Value怎么用?Golang Value使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Value类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: fetchConfig
func fetchConfig(funcname string, name string, config interface{}) bool {
var ret otto.Value
var err error
if name == "" {
ret, err = jsVM.Call(funcname, nil)
} else {
ret, err = jsVM.Call(funcname, nil, name)
}
if err != nil {
log.Printf("call failed, in '%s', %v", funcname, err)
return false
}
jsonConfig, err := ret.ToString()
if err != nil {
log.Println(err)
return false
}
if err := json.Unmarshal([]byte(jsonConfig), config); err != nil {
log.Printf("json.Unmarshal failed, in '%s', %v", funcname, err)
return false
}
return true
}
示例2: ConsiderValue
func (es *ExpressionStats) ConsiderValue(val otto.Value) {
// increment the count
es.Count += 1
if val.IsNumber() {
f, err := val.ToFloat()
if err != nil {
log.Printf("Error converting number to float %v", err)
} else {
// update the sum
es.Sum += f
// if this is smaller than anything we've seen so far update the min
if f < es.Min {
es.Min = f
}
// if this is larger than anything we've seen so far update the max
if f > es.Max {
es.Max = f
}
// update the average (perhaps wasteful, could be done once at the end
// but i'd have to walk the whole tree again, for now will do update it each time
es.Avg = es.Sum / float64(es.Count) // we incremented es.count in this function, can not divide by 0
}
}
}
示例3: findNode
// find the node from the based ont the hash passed in
// the hash needs to at least have a {name: }property
func (js *JavascriptBuilder) findNode(token string, in otto.Value) (n Node, err error) {
var (
givenOptions map[string]interface{}
ok bool
name string
)
e, err := in.Export()
if err != nil {
return n, err
}
// accept both a json hash and a string as an argument.
// if the arg is a hash, then we should extract the name,
// and pull the node from the yaml, and then merge the given options
// over top of the options presented in the config node.
//
// if the arg is a string, then use that string as the name
// and pull the config node
switch arg := e.(type) {
case map[string]interface{}:
givenOptions = arg
if name, ok = givenOptions["name"].(string); ok {
// merge the two maps
tmpMap := make(map[string]interface{})
for k, v := range js.config.Nodes[name] {
tmpMap[k] = v
}
for k, v := range givenOptions {
tmpMap[k] = v
}
givenOptions = tmpMap
} else { // we don't have a name, so lets generate one.
u, err := uuid.NewV4()
if err != nil {
return n, fmt.Errorf("%s error. unable to create uuid (%s)", token, err.Error())
}
name = u.String()
givenOptions["name"] = name
}
case string:
name = arg
givenOptions, ok = js.config.Nodes[name]
if !ok {
return n, fmt.Errorf("%s error. unable to find node '%s'", token, name)
}
}
if token == "transform" {
// this is a little bit of magic so that transformers (which are added by the transform fn get the right kind)
givenOptions["type"] = "transformer"
}
kind, ok := givenOptions["type"].(string)
if !ok {
return n, fmt.Errorf("%s: hash requires a type field, but no type given", token)
}
return NewNode(name, kind, givenOptions)
}
示例4: execScript
// Execute Javascript
func (sh *Shell) execScript(editor bool) stateFn {
var out string
var value otto.Value
var err error
if !editor {
tmp := strings.TrimPrefix(sh.input, RunJavascript) // remove script meta-command
value, err = sh.jsengine.Run(tmp)
} else {
value, err = sh.jsengine.Run(sh.input)
}
if err != nil {
out = err.Error()
} else if value.IsDefined() {
out = value.String()
}
sh.write(out)
if !editor {
sh.line.AppendHistory(sh.input)
}
return bqlPrompt
}
示例5: formatObject
func formatObject(v otto.Value, width, indent, limit, level int, seen map[otto.Value]bool) (string, error) {
if seen[v] {
return strings.Repeat(" ", level*indent) + "[circular]", nil
}
o := v.Object()
bits := []string{"{"}
keys := o.Keys()
for i, k := range keys {
e, err := o.Get(k)
d, err := formatIndent(e, width, indent, limit-1, level+1, len(k)+2, seenWith(seen, v))
if err != nil {
return "", err
}
bits = append(bits, strings.Repeat(" ", (level+1)*indent)+k+": "+d+",")
i++
}
bits = append(bits, strings.Repeat(" ", level*indent)+"}")
return strings.Join(bits, "\n"), nil
}
示例6: formatObjectOneLine
func formatObjectOneLine(v otto.Value, limit int, seen map[otto.Value]bool) (string, error) {
if limit == 0 {
return "...", nil
}
if seen[v] {
return "[circular]", nil
}
o := v.Object()
bits := []string{}
keys := o.Keys()
for _, k := range keys {
e, err := o.Get(k)
if err != nil {
return "", err
}
d, err := formatOneLine(e, limit-1, seenWith(seen, v))
if err != nil {
return "", err
}
bits = append(bits, k+": "+d)
}
return "{" + strings.Join(bits, ", ") + "}", nil
}
示例7: GetInt64
//GetInt64 gets int64 from otto value
func GetInt64(value otto.Value) (result int64, err error) {
result, err = value.ToInteger()
if err != nil {
err = fmt.Errorf(wrongArgumentType, value, "int64")
}
return
}
示例8: runIteratorWithCallback
func runIteratorWithCallback(it graph.Iterator, ses *Session, callback otto.Value, this otto.FunctionCall, limit int) {
count := 0
it, _ = it.Optimize()
for {
if ses.doHalt {
return
}
_, ok := it.Next()
if !ok {
break
}
tags := make(map[string]graph.TSVal)
it.TagResults(&tags)
val, _ := this.Otto.ToValue(tagsToValueMap(tags, ses))
val, _ = callback.Call(this.This, val)
count++
if limit >= 0 && count >= limit {
break
}
for it.NextResult() == true {
if ses.doHalt {
return
}
tags := make(map[string]graph.TSVal)
it.TagResults(&tags)
val, _ := this.Otto.ToValue(tagsToValueMap(tags, ses))
val, _ = callback.Call(this.This, val)
count++
if limit >= 0 && count >= limit {
break
}
}
}
it.Close()
}
示例9: GetBool
//GetBool gets bool from otto value
func GetBool(value otto.Value) (bool, error) {
rawBool, _ := value.Export()
result, ok := rawBool.(bool)
if !ok {
return false, fmt.Errorf(wrongArgumentType, rawBool, "bool")
}
return result, nil
}
示例10: GetAuthorization
//GetAuthorization gets Transaction from otto value
func GetAuthorization(value otto.Value) (schema.Authorization, error) {
rawAuthorization, _ := value.Export()
result, ok := rawAuthorization.(schema.Authorization)
if !ok {
return nil, fmt.Errorf(wrongArgumentType, rawAuthorization, "Authorization")
}
return result, nil
}
示例11: GetTransaction
//GetTransaction gets Transaction from otto value
func GetTransaction(value otto.Value) (transaction.Transaction, error) {
rawTransaction, _ := value.Export()
result, ok := rawTransaction.(transaction.Transaction)
if !ok {
return nil, fmt.Errorf(wrongArgumentType, rawTransaction, "Transaction")
}
return result, nil
}
示例12: GetString
//GetString gets string from otto value
func GetString(value otto.Value) (string, error) {
rawString, _ := value.Export()
result, ok := rawString.(string)
if !ok {
return "", fmt.Errorf(wrongArgumentType, rawString, "string")
}
return result, nil
}
示例13: GetStringList
//GetStringList gets []string from otto value
func GetStringList(value otto.Value) ([]string, error) {
rawSlice, _ := value.Export()
rawResult, ok := rawSlice.([]string)
if !ok {
return make([]string, 0), fmt.Errorf(wrongArgumentType, rawSlice, "array of strings")
}
return rawResult, nil
}
示例14: Filter
func (f *JSFilter) Filter(ev *message.Event) (*message.Event, error) {
var dropped bool
f.vm.Set("$", map[string]interface{}{
"env": f.conf.Env,
"event": map[string]interface{}{
"tag": ev.Tag,
"time": ev.Time,
"record": ev.Record,
},
"drop": func(call otto.FunctionCall) otto.Value {
dropped = true
return otto.Value{}
},
"emit": func(call otto.FunctionCall) (ret otto.Value) {
var record otto.Value
var t time.Time
tag := call.Argument(0).String()
if !call.Argument(2).IsDefined() {
record = call.Argument(1)
t = time.Now()
} else {
record = call.Argument(2)
v, err := call.Argument(1).Export()
if err != nil {
f.env.Log.Warningf("Failed to get time: %v", err)
return
}
var ok bool
t, ok = v.(time.Time)
if !ok {
f.env.Log.Warningf("Failed to get time: unsupported type %T", v)
return
}
}
rec, err := record.Export()
if err != nil {
f.env.Log.Warningf("Failed to get record: %v", err)
return
}
typedRec, ok := rec.(map[string]interface{})
if !ok {
f.env.Log.Warningf("Failed to get record: Unsupported type %T", rec)
return
}
f.env.Emit(message.NewEventWithTime(tag, t, typedRec))
return
},
})
_, err := f.vm.Run(f.script)
if err != nil {
return nil, err
} else if dropped {
return nil, nil
}
return ev, nil
}
示例15: GetMap
//GetMap gets map[string]interface{} from otto value
func GetMap(value otto.Value) (map[string]interface{}, error) {
rawMap, _ := value.Export()
result, ok := rawMap.(map[string]interface{})
if !ok {
return map[string]interface{}{}, fmt.Errorf(wrongArgumentType, rawMap, "Object")
}
for key, value := range result {
result[key] = ConvertOttoToGo(value)
}
return result, nil
}