當前位置: 首頁>>代碼示例>>Golang>>正文


Golang Otto.Set方法代碼示例

本文整理匯總了Golang中github.com/robertkrimen/otto.Otto.Set方法的典型用法代碼示例。如果您正苦於以下問題:Golang Otto.Set方法的具體用法?Golang Otto.Set怎麽用?Golang Otto.Set使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/robertkrimen/otto.Otto的用法示例。


在下文中一共展示了Otto.Set方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Bind

// Bind binds the method to the specified runtime.
func (m *Method) Bind(runtime *otto.Otto) error {
	castFunc := (func(call otto.FunctionCall) otto.Value)(m.Func)
	if err := runtime.Set("$$"+m.Name, castFunc); err != nil {
		return err
	}
	return nil
}
開發者ID:jmptrader,項目名稱:pangaea,代碼行數:8,代碼來源:methods.go

示例2: addDiscoveryService

func (ctrl *JsController) addDiscoveryService(o *otto.Otto) {
	o.Set("discover", func(call otto.FunctionCall) otto.Value {
		if len(call.ArgumentList) == 0 {
			glog.Errorf("DISCOVER: Missing arguments")
			return otto.NullValue()
		}

		url, _ := call.Argument(0).ToString()
		upstreams, err := ctrl.DiscoveryService.Get(url)
		if err != nil {
			glog.Errorf("Failed to discover upstreams: %v", err)
			return otto.NullValue()
		}

		glog.Infof("Discovered upstreams: %v", upstreams)

		result, err := o.ToValue(upstreams)
		if err != nil {
			glog.Errorf("Failed to convert: %v", err)
			return otto.NullValue()
		}

		return result
	})
}
開發者ID:johntdyer,項目名稱:golang-devops-stuff,代碼行數:25,代碼來源:js.go

示例3: NewWriter

// NewWriter adds a write method to the specified runtime that allows
// client code to write to the specified io.Writer.
//
// The client function created has the following syntax:
//
//     var response = writeMethodName(contentToWrite)
//
// Response object:
//
//     {
//       len: bytes_written,
//        error: error|undefined
//     }
func NewWriter(runtime *otto.Otto, methodName string, writer io.Writer) error {

	runtime.Set(methodName, func(call otto.FunctionCall) otto.Value {

		var data string
		var count int
		var err error
		var val otto.Value

		if data, err = call.Argument(0).ToString(); err == nil {
			if count, err = writer.Write([]byte(data)); err == nil {
				if val, err = makeMap(runtime, map[string]interface{}{"len": count}); err != nil {
					raiseError(runtime, "Failed to create output object: %s", err)
				} else {
					return val
				}
			}
		}

		if err != nil {
			if val, err := makeMap(runtime, map[string]interface{}{"len": 0, "error": err.Error()}); err != nil {
				raiseError(runtime, "Failed to create output object: %s", err)
				return otto.UndefinedValue()
			} else {
				return val
			}
		}

		return otto.UndefinedValue()

	})

	return nil
}
開發者ID:jmptrader,項目名稱:ottox,代碼行數:47,代碼來源:writer.go

示例4: Sync

func (b Buffers) Sync(o *otto.Otto) error {
	if v, err := o.ToValue(b); err != nil {
		return err
	} else {
		o.Set("buffers", v)
	}
	return nil
}
開發者ID:janne,項目名稱:janitor,代碼行數:8,代碼來源:buffer.go

示例5: addLoggers

func (ctrl *JsController) addLoggers(o *otto.Otto) {
	o.Set("info", func(call otto.FunctionCall) otto.Value {
		return log("info", call)
	})
	o.Set("error", func(call otto.FunctionCall) otto.Value {
		return log("error", call)
	})

}
開發者ID:johntdyer,項目名稱:golang-devops-stuff,代碼行數:9,代碼來源:js.go

示例6: InitEnv

func InitEnv(vm *otto.Otto) {
	vm.Set("G", new(Env))

	vm.Set("toJS", func(call otto.FunctionCall) otto.Value {
		result, err := vm.ToValue(call.Argument(0))
		if err != nil {
			panic(err)
		}
		return result
	})
}
開發者ID:jsmorph,項目名稱:tinygraph,代碼行數:11,代碼來源:repl.go

示例7: RegisterMethodFileOpen

// 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
}
開發者ID:jmptrader,項目名稱:ottox,代碼行數:73,代碼來源:files.go

示例8: SetOttoVM

func SetOttoVM(vm *otto.Otto, pmap map[string]string, key string, ptype string) {
	if value, ok := pmap[key]; ok {
		switch ptype {
		case "string":
			vm.Set(key, value)
		case "int":
			intval, err := strconv.Atoi(value)
			if err != nil {
				log.Println(err.Error())
			} else {
				vm.Set(key, intval)
			}
		}
	}
}
開發者ID:donh,項目名稱:query,代碼行數:15,代碼來源:computeFuncHelper.go

示例9: SetOnce

// SetOnce sets a name or value only if it doesn't exist.
//
// Returns whether the value was set or not, or an error if it failed to
// set it.
//
// For acceptable values, see http://godoc.org/github.com/robertkrimen/otto#Otto.Set
func SetOnce(runtime *otto.Otto, name string, value interface{}) (bool, error) {

	if !Exist(runtime, name) {

		if err := runtime.Set(name, value); err != nil {
			return false, err
		}

		return true, nil

	}

	// nothing to do
	return false, nil

}
開發者ID:jmptrader,項目名稱:ottox,代碼行數:22,代碼來源:set.go

示例10: setValueAtPath

func setValueAtPath(context *otto.Otto, path string, value interface{}) {
	parts := strings.Split(path, ".")
	parentCount := len(parts) - 1
	if parentCount > 0 {
		parentPath := strings.Join(parts[0:parentCount], ".")
		parent, err := context.Object("(" + parentPath + ")")
		if err != nil {
			emptyObject, _ := context.Object(`({})`)
			setValueAtPath(context, parentPath, emptyObject)
		}
		parent, _ = context.Object("(" + parentPath + ")")
		parent.Set(parts[parentCount], value)
	} else {
		context.Set(path, value)
	}
}
開發者ID:rcoelho,項目名稱:go-plugins,代碼行數:16,代碼來源:ottojs.go

示例11: Define

func Define(vm *otto.Otto, argv []string) error {
	if v, err := vm.Get("process"); err != nil {
		return err
	} else if !v.IsUndefined() {
		return nil
	}

	env := make(map[string]string)
	for _, e := range os.Environ() {
		a := strings.SplitN(e, "=", 2)
		env[a[0]] = a[1]
	}

	return vm.Set("process", map[string]interface{}{
		"env":  env,
		"argv": argv,
	})
}
開發者ID:deoxxa,項目名稱:ottoext,代碼行數:18,代碼來源:process.go

示例12: createContext

func createContext(vm *otto.Otto, event chan otto.Value) otto.Value {
	var cbfunc = func(invar ...interface{}) {
		var lovar otto.Value
		if len(invar) > 0 {
			lovar, _ = vm.ToValue(invar[0])
		} else {
			lovar = otto.NullValue()
		}
		event <- lovar
		close(event)
	}
	vm.Set("_iopipe_cb", cbfunc)
	vm.Run(`_iopipe_context = { "done": _iopipe_cb,
                                    "success": _iopipe_cb,
                                    "fail": _iopipe_cb }`)
	jscontext, _ := vm.Get("_iopipe_context")
	return jscontext
}
開發者ID:ewindisch,項目名稱:iopipe,代碼行數:18,代碼來源:filter.go

示例13: InitializeRuntime

// InitializeRuntime initializes a runtime, setting classes avaible in scripting etc
// This returns the first runtime error
func (api *API) InitializeRuntime(runtime *otto.Otto, object *Object) error {
	var engErr, objErr, inErr error
	engErr = runtime.Set("engine", NewEngineInterface(api.base))
	objErr = runtime.Set("object", NewObjectInterface(object))
	inErr = runtime.Set("input", NewInputInterface(api.base.Input()))
	return checkAnyError(engErr, objErr, inErr)
}
開發者ID:j6n,項目名稱:Not3D,代碼行數:9,代碼來源:interface.go

示例14: loadDefaults

func loadDefaults(runtime *otto.Otto) error {
	if err := runtime.Set("defaultTTL", ttl); err != nil {
		return err
	}
	if err := runtime.Set("defaultEnvironment", environment); err != nil {
		return err
	}
	if err := runtime.Set("cleanImageName", func(call otto.FunctionCall) otto.Value {
		name := call.Argument(0).String()
		result, _ := otto.ToValue(utils.CleanImageName(name))
		return result
	}); err != nil {
		return err
	}
	if err := runtime.Set("removeSlash", func(call otto.FunctionCall) otto.Value {
		name := call.Argument(0).String()
		result, _ := otto.ToValue(utils.RemoveSlash(name))
		return result
	}); err != nil {
		return err
	}
	return nil
}
開發者ID:tomzhang,項目名稱:golang-devops-stuff,代碼行數:23,代碼來源:plugins.go

示例15: NewReader

// NewReader adds a read method to the specified runtime that allows
// client code to read from the specified reader.
//
// The client function created has the following syntax:
//
//     var response = readMethodName(bytesToRead);
//
// Response object:
//
//     {
//       data: "This was read from the reader.",
//       eof: false|true,
//       error: error|undefined
//     }
//
// If eof is false, client code should keep calling the read method
// until all data has been read.
//
// For example, to stream from the Stdin pipe:
//
//     // in go...
//     NewReader(js, "readStdIn", os.Stdin)
//
//     // in a script...
//     var data = "";
//     var response = {"eof":false};
//     while (!response.eof) {
//       response = readStdIn(255);
//       data += response.data;
//     }
//
// Passing -1 as the bytesToRead will read the entire contents from
// the reader immediately.
func NewReader(runtime *otto.Otto, methodName string, reader io.Reader) error {

	runtime.Set(methodName, func(call otto.FunctionCall) otto.Value {

		var err error
		var l int64
		var all []byte
		var val otto.Value
		var bytesRead int

		if l, err = call.Argument(0).ToInteger(); err != nil {
			raiseError(runtime, "First argument to read methods must be an integer: %s", err)
		} else {

			if l == -1 {

				all, err = ioutil.ReadAll(reader)
				if err != nil {
					raiseError(runtime, "Failed to read from io.Reader: %s", err)
				} else {

					if val, err = makeMap(runtime, map[string]interface{}{"data": string(all), "eof": true}); err != nil {
						raiseError(runtime, "Failed to create output object: %s", err)
					} else {
						return val
					}

				}

			} else {

				// read x bytes from the reader
				buf := make([]byte, l)
				bytesRead, err = reader.Read(buf)
				var isEof bool = false
				if err == io.EOF {
					isEof = true
				} else if err != nil {
					raiseError(runtime, "Failed to read from io.Reader: %s", err)
				}

				// get the data
				var dataStr string
				if bytesRead > 0 {
					dataStr = string(buf)
				}

				if val, err = makeMap(runtime, map[string]interface{}{"data": dataStr, "eof": isEof}); err != nil {
					raiseError(runtime, "Failed to create output object: %s", err)
				} else {
					return val
				}

			}

		}

		if err != nil {
			if val, err := makeMap(runtime, map[string]interface{}{"eof": true, "error": err.Error()}); err != nil {
				raiseError(runtime, "Failed to create output object: %s", err)
				return otto.UndefinedValue()
			} else {
				return val
			}
		}

		// nothing to return
//.........這裏部分代碼省略.........
開發者ID:jmptrader,項目名稱:ottox,代碼行數:101,代碼來源:reader.go


注:本文中的github.com/robertkrimen/otto.Otto.Set方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。