当前位置: 首页>>代码示例>>Golang>>正文


Golang otto.New函数代码示例

本文整理汇总了Golang中github.com/robertkrimen/otto.New函数的典型用法代码示例。如果您正苦于以下问题:Golang New函数的具体用法?Golang New怎么用?Golang New使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了New函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: NewOttoGrouper

func NewOttoGrouper() *OttoGrouper {
	return &OttoGrouper{
		OutputChannel: make(DocumentChannel),
		Otto:          otto.New(),
		groupValues:   make(map[string]ExpressionStatsMap),
		groupDocs:     make(map[string]Document)}
}
开发者ID:mschoch,项目名称:tuq,代码行数:7,代码来源:otto_grouper.go

示例2: main

func main() {
	flag.Parse()
	var script []byte
	var err error
	filename := flag.Arg(0)
	if filename == "" || filename == "-" {
		script, err = ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Printf("Can't read stdin: %v\n", err)
			os.Exit(64)
		}
	} else {
		script, err = ioutil.ReadFile(filename)
		if err != nil {
			fmt.Printf("Can't open file \"%v\": %v\n", filename, err)
			os.Exit(64)
		}
	}
	if !*underscoreFlag {
		underscore.Disable()
	}
	Otto := otto.New()
	_, err = Otto.Run(string(script))
	if err != nil {
		fmt.Println(err)
		os.Exit(64)
	}
}
开发者ID:adrianuswarmenhoven,项目名称:otto,代码行数:28,代码来源:main.go

示例3: initJs

func initJs(t *testing.T) *otto.Otto {
	var otto = otto.New()
	soyutilsFile, err := os.Open("lib/soyutils.js")
	if err != nil {
		panic(err)
	}
	// remove any non-otto compatible regular expressions
	var soyutilsBuf bytes.Buffer
	var scanner = bufio.NewScanner(soyutilsFile)
	var i = 1
	for scanner.Scan() {
		switch i {
		case 2565, 2579, 2586:
			// skip these regexes
			// soy.esc.$$FILTER_FOR_FILTER_CSS_VALUE_
			// soy.esc.$$FILTER_FOR_FILTER_HTML_ATTRIBUTES_
			// soy.esc.$$FILTER_FOR_FILTER_HTML_ELEMENT_NAME_
		default:
			soyutilsBuf.Write(scanner.Bytes())
			soyutilsBuf.Write([]byte("\n"))
		}
		i++
	}
	// load the soyutils library
	_, err = otto.Run(soyutilsBuf.String())
	if err != nil {
		t.Errorf("soyutils error: %v", err)
		panic(err)
	}
	return otto
}
开发者ID:leobcn,项目名称:soy,代码行数:31,代码来源:exec_test.go

示例4: Calculate

func Calculate(response http.ResponseWriter, request *http.Request, params martini.Params) {
	bodyBytes, err := ioutil.ReadAll(request.Body)
	if err != nil {
		return
	}

	var toCalc Calculation
	err = json.Unmarshal(bodyBytes, &toCalc)
	if err != nil {
		http.Error(response, "Failed to Parse JSON", http.StatusInternalServerError)
		return
	}
	if toCalc.Calculation == "" {
		return
	}
	runner := otto.New()
	result, err := runner.Run(toCalc.Calculation)
	if err != nil {
		http.Error(response, err.Error(), http.StatusInternalServerError)
		return
	}
	toCalc.Result, _ = result.ToFloat()
	responseBytes, err := json.Marshal(toCalc)
	if err != nil {
		http.Error(response, "Failed to Encode JSON", http.StatusInternalServerError)
		return
	}

	fmt.Fprint(response, string(responseBytes))
	return
}
开发者ID:Prometheus-SCN,项目名称:Prometheus,代码行数:31,代码来源:server.go

示例5: NewScripting

func NewScripting() (s *Scripting, err error) {
	s = &Scripting{
		vm:        otto.New(),
		listeners: map[string][]otto.Value{},
	}
	return
}
开发者ID:pikkpoiss,项目名称:twodee,代码行数:7,代码来源:script.go

示例6: NewJavascriptBuilder

// NewJavascriptBuilder compiles the supplied javascript and creates a Javascriptbulder
func NewJavascriptBuilder(config Config, file, src string) (*JavascriptBuilder, error) {
	js := &JavascriptBuilder{
		file:      file,
		vm:        otto.New(),
		path:      filepath.Dir(file),
		config:    config,
		nodes:     make(map[string]Node),
		pipelines: make([]*transporter.Pipeline, 0),
	}

	var (
		script *otto.Script
		err    error
	)
	if src != "" {
		script, err = js.vm.Compile("", src)
	} else {
		script, err = js.vm.Compile(file, nil)
	}

	if err != nil {
		return js, err
	}
	js.script = script
	js.vm.Set("Source", js.source)

	return js, nil
}
开发者ID:Garyguo110,项目名称:transporter,代码行数:29,代码来源:javascript_builder.go

示例7: NewChannelMapper

func NewChannelMapper(funcSource string) (*ChannelMapper, error) {
	mapper := &ChannelMapper{}
	mapper.js = otto.New()

	// Implementation of the 'sync()' callback:
	mapper.js.Set("sync", func(call otto.FunctionCall) otto.Value {
		for _, arg := range call.ArgumentList {
			if arg.IsString() {
				mapper.channels = append(mapper.channels, arg.String())
			} else if arg.Class() == "Array" {
				array := ottoArrayToStrings(arg.Object())
				if array != nil {
					mapper.channels = append(mapper.channels, array...)
				}
			}
		}
		return otto.UndefinedValue()
	})

	if _, err := mapper.setFunction(funcSource); err != nil {
		return nil, err
	}

	mapper.requests = make(chan channelMapperRequest)
	go mapper.serve()

	return mapper, nil
}
开发者ID:escoz,项目名称:basecouch,代码行数:28,代码来源:channelmapper.go

示例8: TestFetchWithHandlerParallel

func TestFetchWithHandlerParallel(t *testing.T) {
	m := http.NewServeMux()
	m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello"))
	})

	vm := otto.New()
	l := loop.New(vm)

	if err := DefineWithHandler(vm, l, m); err != nil {
		panic(err)
	}

	ch := make(chan bool, 1)

	if err := vm.Set("__capture", func(c otto.FunctionCall) otto.Value {
		defer func() { ch <- true }()

		return otto.UndefinedValue()
	}); err != nil {
		panic(err)
	}

	must(l.EvalAndRun(`Promise.all([1,2,3,4,5].map(function(i) { return fetch('/' + i); })).then(__capture)`))

	<-ch
}
开发者ID:deoxxa,项目名称:ottoext,代码行数:27,代码来源:fetch_test.go

示例9: TestOttoFromGoArray

func TestOttoFromGoArray(t *testing.T) {
	o := otto.New()
	_, err := OttoFromGoArray(o, nil)
	if err == nil {
		t.Errorf("expected err for nil array to OttoFromGoArray")
	}
}
开发者ID:steveyen,项目名称:cbgb,代码行数:7,代码来源:js_test.go

示例10: NewAnnotator

// NewAnnotator returns an Annotator with the sources, seeded with some javascript.
// If ends is true, it will annotate the 1 base ends of the interval as well as the
// interval itself. If strict is true, when overlapping variants, they must share
// the ref allele and at least 1 alt allele.
func NewAnnotator(sources []*Source, js string, ends bool, strict bool) *Annotator {
	for _, s := range sources {
		if e := checkSource(s); e != nil {
			log.Fatal(e)
		}
	}
	a := Annotator{
		Sources: sources,
		Strict:  strict,
		Ends:    ends,
	}
	for _, src := range a.Sources {
		src.Vm = otto.New() // create a new vm for each source and lock in the source
		if strings.HasPrefix(src.Op, "js:") {
			var err error
			src.Js, err = src.Vm.Compile(src.Op, src.Op[3:])
			if err != nil {
				log.Fatalf("error parsing op: %s for file %s", src.Op, src.File)
			}
		}
		if js != "" {
			_, err := src.Vm.Run(js)
			if err != nil {
				log.Fatalf("error parsing customjs:%s", err)
			}
		}
	}
	return &a
}
开发者ID:MMesbahU,项目名称:vcfanno,代码行数:33,代码来源:api.go

示例11: main

func main() {
	flag.Parse()

	if !*flag_underscore {
		underscore.Disable()
	}

	err := func() error {
		src, err := readSource(flag.Arg(0))
		if err != nil {
			return err
		}

		vm := otto.New()
		g_vm = vm

		vm.Set("setRoute", setRoute)
		vm.Set("startServer", startServer)
		vm.Set("writeMessage", writeMessage)

		_, err = vm.Run(src)
		return err
	}()
	if err != nil {
		switch err := err.(type) {
		case *otto.Error:
			fmt.Print(err.String())
		default:
			fmt.Println(err)
		}
		os.Exit(64)
	}
}
开发者ID:khanht-nguyen,项目名称:Newton,代码行数:33,代码来源:Newton.go

示例12: createVM

func createVM() *otto.Otto {
	vm := otto.New()

	logObj, _ := vm.Object(`$log = {}`)
	logObj.Set("info", _log_info)

	fileObj, _ := vm.Object(`$file = {}`)
	fileObj.Set("exists", _file_exists)
	fileObj.Set("write", _file_write)
	fileObj.Set("copy", _file_copy)
	fileObj.Set("size", _file_size)
	fileObj.Set("move", _file_move)
	fileObj.Set("mkdir", _file_mkdir)
	fileObj.Set("delete", _file_delete)
	fileObj.Set("readString", _file_readString)

	requestObj, _ := vm.Object(`$request = {}`)
	requestObj.Set("download", _request_download)
	requestObj.Set("get", _request_get)

	systemObj, _ := vm.Object(`$system = {}`)
	systemObj.Set("executeAndRead", _system_executeAndRead)
	systemObj.Set("execute", _system_execute)
	systemObj.Set("detach", _system_detach)
	systemObj.Set("currentUser", _system_currentUser)
	systemObj.Set("kill", _system_kill)

	return vm
}
开发者ID:cgmarquis07,项目名称:Conduit,代码行数:29,代码来源:engine.go

示例13: main

func main() {

	vm := otto.New()

	s, _ := simplejson.NewJson([]byte(`
	{"name":"[{\"name\":\"全部\",\"value\":\"all\"},{\"value\":372,\"name\":\"家居个护\"},{\"value\":437,\"name\":\"美容彩妆\"},{\"value\":438,\"name\":\"母婴\"},{\"value\":440,\"name\":\"数码家电\"},{\"value\":636,\"name\":\"【多余类目\"},{\"value\":836,\"name\":\"环球美食\"},{\"value\":837,\"name\":\"营养保健\"},{\"value\":1025,\"name\":\"箱包配饰\"},{\"value\":7578,\"name\":\"运动户外\"},{\"value\":8115,\"name\":\"生鲜\"},{\"value\":9691,\"name\":\"服装鞋靴\"}]"}
	`))
	//fmt.Println(s.Get("name").MustMap())
	vm.Set("def", s.Get("name").MustString())
	vm.Set("getArray", func(call otto.FunctionCall) otto.Value {
		result, _ := vm.ToValue(getArray(call.Argument(0).String(), call.Argument(1).String()))
		return result
	})
	vm.Set("getMap", func(call otto.FunctionCall) otto.Value {
		result, _ := vm.ToValue(getMap(call.Argument(0).String(), call.Argument(1).String()))
		return result
	})
	_, e := vm.Run(`
	//var x = [];
	//x=x.concat(eval(def))
	//	console.log(x[0].name)
		//console.log(x.push(1))
		//var x = {category_level:1};
    		//var x = JSON.parse(getData('http://localhost:8080/ds/50',JSON.stringify({name:1,age:19})));
    		//console.log(x.data)
    		//console.log(x.code)
    		console.log(getArray('http://www.jeasyui.com/demo/main/treegrid_data1.json')[0].id)
	`)
	if e != nil {
		fmt.Println(e)
	}
}
开发者ID:ywshz,项目名称:mygods,代码行数:32,代码来源:test6.go

示例14: TestNewReader_ReadAll

func TestNewReader_ReadAll(t *testing.T) {

	runtime := otto.New()
	reader := strings.NewReader("Hello ottox!")

	assert.NoError(t, NewReader(runtime, "read", reader))

	// make sure ottox.read method was added
	assert.True(t, Exist(runtime, "read"))

	// read some bytes
	if r, err := runtime.Call(`read`, nil, -1); assert.NoError(t, err) {
		if res, err := r.Object().Get("data"); assert.NoError(t, err) {
			if bytes, err := res.ToString(); assert.NoError(t, err) {
				assert.Equal(t, bytes, "Hello ottox!", "data")
			}
		}
		if res, err := r.Object().Get("eof"); assert.NoError(t, err) {
			if eofBool, err := res.ToBoolean(); assert.NoError(t, err) {
				assert.True(t, eofBool, "eof")
			}
		}
	}

}
开发者ID:jmptrader,项目名称:ottox,代码行数:25,代码来源:reader_test.go

示例15: HTTPMiddlewarePreRequest

func HTTPMiddlewarePreRequest(endpoint *kasi_conf.EndpointSetting, r *http.Request) *MiddlewareResponse {
	for i := 0; i < len(endpoint.Middleware); i++ {
		jsFile, err := ioutil.ReadFile(endpoint.Middleware[i])
		if err != nil {
			log.Error("javascript file, `%v`, not found", i)
			continue
		}
		vm := otto.New()
		vm.Run(jsFile)

		request := *r
		requestJS, _ := vm.ToValue(&request)

		response := MiddlewareResponse{StatusCode: 0, Header: map[string]string{}, Body: ""}
		responseJS, _ := vm.ToValue(&response)

		returnedResponse, err := vm.Call("process_request", nil, requestJS, responseJS)
		if err != nil {
			log.Error("failed to call, %v", err)
			continue
		}

		if !returnedResponse.IsDefined() {
			continue
		}

		exportedResponseReady, err := returnedResponse.Export()
		if err == nil {
			return exportedResponseReady.(*MiddlewareResponse)
		}
		break
	}

	return nil
}
开发者ID:haiheipijuan,项目名称:kasi,代码行数:35,代码来源:http.go


注:本文中的github.com/robertkrimen/otto.New函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。