當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。