v8

package module
v0.0.0-...-362f052 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2023 License: MIT Imports: 9 Imported by: 3

README

v8.go

V8 JavaScript engine bindings for Go.

Features

  • Thread safe
  • Thorough and careful testing
  • Boolean, Number, String, Object, Array, Regexp, Function
  • Compile and run JavaScript
  • Create JavaScript context with global object template
  • Operate JavaScript object properties and array elements in Go
  • Define JavaScript object template in Go with property accessors and interceptors
  • Define JavaScript function template in Go
  • Catch JavaScript exception in Go
  • Throw JavaScript exception by Go
  • JSON parse and generate
  • Powerful binding API
  • C++ plugin

Install

For 'curl' user. please run this shell command:

curl -OL https://raw.github.com/Joker2333/v8.go/master/get.sh && chmod +x get.sh && ./get.sh v8.go

For 'wget' user. Please run this shell command:

wget https://raw.github.com/Joker2333/v8.go/master/get.sh && chmod +x get.sh && ./get.sh v8.go

Note: require Go version 1.2 and Git.

Hello World

This 'Hello World' program shows how to use v8.go to compile and run JavaScript code then get the result.

package main

import "github.com/Joker2333/v8.go"

func main() {
	engine := v8.NewEngine()
	script := engine.Compile([]byte("'Hello ' + 'World!'"), nil)
	context := engine.NewContext(nil)

	context.Scope(func(cs v8.ContextScope) {
		result := cs.Run(script)
		println(result.ToString())
	})
}

Fast Binding

package main

import "fmt"
import "github.com/Joker2333/v8.go"

type MyType struct {
	Id       int
	Name     string
	Data     map[string]int
	Callback func(a int, b string)
}

func (mt *MyType) Dump(info string) {
	fmt.Printf(
		"Info: \"%s\", Id: %d, Name: \"%s\", Data: %v\n",
		info, mt.Id, mt.Name, mt.Data,
	)
}

func main() {
	engine := v8.NewEngine()

	global := engine.NewObjectTemplate()

	global.Bind("MyType", MyType{})

	global.Bind("print", func(v ...interface{}) {
		fmt.Println(v...)
	})

	global.Bind("test", func(obj *v8.Object) {
		raw := obj.GetInternalField(0).(*v8.BindObject)
		raw.Target.Interface().(*MyType).Callback(123, "dada")
	})

	engine.NewContext(global).Scope(func(cs v8.ContextScope) {
		cs.Eval(`
			var a = new MyType();

			a.Dump("old");

			a.Id = 10;
			a.Name = "Hello";
			a.Data = {
				'x': 1,
				'y': 2
			};
			a.Dump("new");

			a.Callback = function(a, b) {
				print(a, b);
			}

			a.Callback(10, "Hello");

			test(a);
		`)
	})
}

C++ plugin

You can implement plugin in C++.

#include "v8.h"
#include "v8_plugin.h"

using namespace v8;

extern "C" {

static void LogCallback(const FunctionCallbackInfo<Value>& args) {
	if (args.Length() < 1) return;

	HandleScope scope(args.GetIsolate());
	Handle<Value> arg = args[0];
	String::Utf8Value value(arg);

	printf("%s\n", *value);
}

v8_export_plugin(log, {
	global->Set(isolate, "log",
		FunctionTemplate::New(isolate, LogCallback)
	);
});

}

And load the plugin in Go.

package main

/*
#cgo pkg-config: ../../v8.pc

#include "v8_plugin.h"

v8_import_plugin(log);
*/
import "C"
import "github.com/Joker2333/v8.go"

func main() {
	engine := v8.NewEngine()
	global := engine.NewObjectTemplate()

	// C.v8_plugin_log generate by v8_import_plugin(log)
	global.Plugin(C.v8_plugin_log)

	engine.NewContext(global).Scope(func(cs v8.ContextScope) {
		cs.Eval(`
			log("Hello Plugin!")
		`)
	})
}

Performance and Stability

The benchmark result on my iMac:

Benchmark_NewContext   285869 ns/op
Benchmark_NewInteger      707 ns/op
Benchmark_NewString      1869 ns/op
Benchmark_NewObject      3292 ns/op
Benchmark_NewArray0      1004 ns/op
Benchmark_NewArray5      4024 ns/op
Benchmark_NewArray20     8601 ns/op
Benchmark_NewArray100   31963 ns/op
Benchmark_Compile      640988 ns/op
Benchmark_RunScript       888 ns/op
Benchmark_JsFunction     1148 ns/op
Benchmark_GoFunction     1491 ns/op
Benchmark_Getter         2215 ns/op
Benchmark_Setter         3261 ns/op
Benchmark_TryCatch      47366 ns/op

Concepts

Engine

In v8.go, engine type is the wrapper of v8::Isolate.

Because V8 engine use thread-local storage but cgo calls may be execute in different thread. So v8.go use v8::Locker to make sure V8 engine's thread-local data initialized. And the locker make v8.go thread safe.

You can create different engine instance for data isolate or improve efficiency of concurrent purpose.

engine1 := v8.NewEngine()
engine2 := v8.NewEngine()

Script

When you want to run some JavaScript. You need to compile first.

Scripts can run many times or run in different context.

script := engine.Compile([]byte(`"Hello " + "World!"`), nil)

The Engine.Compile() method take 2 arguments.

The first is the code.

The second is a ScriptOrigin, it stores script's file name or line number offset etc. You can use ScriptOrigin to make error message and stack trace friendly.

name := "my_file.js"
real := ReadFile(name)
code := "function(_export){\n" + real + "\n}"
origin := engine.NewScriptOrigin(name, 1, 0)
script := engine.Compile(code, origin, nil)

Context

The description in V8 embedding guide:

In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.

In v8.go, you can create many contexts from a V8 engine instance. When you want to run some JavaScript in a context. You need to enter the context by calling Scope() and run the JavaScript in the callback.

context.Scope(func(cs v8.ContextScope){
	script.Run()
})

Context in V8 is necessary. So in v8.go you can do this:

context.Scope(func(cs v8.ContextScope) {
	context2 := engine.NewContext(nil)
	context2.Scope(func(cs2 v8.ContextScope) {

	})
})

More

Please read v8_all_test.go and the codes in samples folder.

中文介绍

V8引擎的Go语言绑定。

特性

  • 线程安全
  • 详细的测试
  • 数据类型:Boolean, Number, String, Object, Array, Regexp, Function
  • 编译并运行JavaScript
  • 创建带有全局对象模板的Context
  • 在Go语言端操作和访问JavaScript数组的元素
  • 在Go语言端操作和访问JavaScript对象的属性
  • 用Go语言创建支持属性访问器和拦截器的JavaScript对象模板
  • 用Go语言创建JavaScript函数模板
  • 在Go语言端捕获JavaScript的异常
  • 从Go语言端抛出JavaScript的异常
  • JSON解析和生成
  • 强大的绑定功能
  • C++插件机制

安装

'curl'用户请运行以下脚本:

curl -O https://raw.github.com/Joker2333/v8.go/master/get.sh && chmod +x get.sh && ./get.sh v8.go

'wget'用户请运行以下脚本:

wget https://raw.github.com/Joker2333/v8.go/master/get.sh && chmod +x get.sh && ./get.sh v8.go

需求本地安装有Go 1.2和git命令。

Hello World

以下是一段Hello World程序,用来展示v8.go如何编译和运行JavaScript并获得结果:

package main

import "github.com/Joker2333/v8.go"

func main() {
	engine := v8.NewEngine()
	script := engine.Compile([]byte("'Hello ' + 'World!'"), nil)
	context := engine.NewContext(nil)

	context.Scope(func(cs v8.ContextScope) {
		result := cs.Run(script)
		println(result.ToString())
	})
}

快速绑定

package main

import "fmt"
import "reflect"
import "github.com/Joker2333/v8.go"

type MyType struct {
	Id       int
	Name     string
	Data     map[string]int
	Callback func(a int, b string)
}

func (mt *MyType) Dump(info string) {
	fmt.Printf(
		"Info: \"%s\", Id: %d, Name: \"%s\", Data: %v\n",
		info, mt.Id, mt.Name, mt.Data,
	)
}

func main() {
	engine := v8.NewEngine()

	global := engine.NewObjectTemplate()

	global.Bind("MyType", MyType{})

	global.Bind("print", func(v ...interface{}) {
		fmt.Println(v...)
	})

	global.Bind("test", func(obj *v8.Object) {
		raw := obj.GetInternalField(0).(*reflect.Value)
		raw.Interface().(*MyType).Callback(123, "dada")
	})

	engine.NewContext(global).Scope(func(cs v8.ContextScope) {
		cs.Eval(`
			var a = new MyType();

			a.Dump("old");

			a.Id = 10;
			a.Name = "Hello";
			a.Data = {
				'x': 1,
				'y': 2
			};
			a.Dump("new");

			a.Callback = function(a, b) {
				print(a, b);
			}

			a.Callback(10, "Hello");

			test(a);
		`)
	})
}

C++插件机制

你可以用C++实现插件.

#include "v8.h"
#include "v8_plugin.h"

using namespace v8;

extern "C" {

static void LogCallback(const FunctionCallbackInfo<Value>& args) {
	if (args.Length() < 1) return;

	HandleScope scope(args.GetIsolate());
	Handle<Value> arg = args[0];
	String::Utf8Value value(arg);

	printf("%s\n", *value);
}

v8_export_plugin(log, {
	global->Set(isolate, "log",
		FunctionTemplate::New(isolate, LogCallback)
	);
});

}

并在Go代码中加载它.

package main

/*
#cgo pkg-config: ../../v8.pc

#include "v8_plugin.h"

v8_import_plugin(log);
*/
import "C"
import "github.com/Joker2333/v8.go"

func main() {
	engine := v8.NewEngine()
	global := engine.NewObjectTemplate()

	// C.v8_plugin_log generate by v8_import_plugin(log)
	global.Plugin(C.v8_plugin_log)

	engine.NewContext(global).Scope(func(cs v8.ContextScope) {
		cs.Eval(`
			log("Hello Plugin!")
		`)
	})
}

性能和稳定性

以下是在我的iMac上运行benchmark的输出结果:

Benchmark_NewContext   285869 ns/op
Benchmark_NewInteger      707 ns/op
Benchmark_NewString      1869 ns/op
Benchmark_NewObject      3292 ns/op
Benchmark_NewArray0      1004 ns/op
Benchmark_NewArray5      4024 ns/op
Benchmark_NewArray20     8601 ns/op
Benchmark_NewArray100   31963 ns/op
Benchmark_Compile      640988 ns/op
Benchmark_RunScript       888 ns/op
Benchmark_JsFunction     1148 ns/op
Benchmark_GoFunction     1491 ns/op
Benchmark_Getter         2215 ns/op
Benchmark_Setter         3261 ns/op
Benchmark_TryCatch      47366 ns/op

概念

Engine

在v8.go中,Engine类型是对象v8::Isolate的封装。

因为V8引擎使用线程相关的存储机制用来优化性能,但是CGO调用可能会在不同的线程里执行。所以v8.go使用v8::Locker来确定V8引擎的线程数据有初始化,并确保v8.go是线程安全的。

你可以创建多个引擎实例用来隔离数据和优化并发效率。

engine1 := v8.NewEngine()
engine2 := v8.NewEngine()

Script

当你要运行一段JavaScript代码前,你需要先把它编译成Script对象。

一个Script对象可以在不同的Context中运行多次。

script := engine.Compile([]byte(`"Hello " + "World!"`), nil)

Engine.Compile()方法需要三个参数。

第一个参数是所要编译的JavaScript代码。

第二个参数是一个ScriptOrigin对象,其中存储着脚本对应的文件名和行号等。你可以用ScriptOrigin来让错误信息和栈跟踪信息更友好。

name := "my_file.js"
real := ReadFile(name)
code := "function(_export){\n" + real + "\n}"
origin := engine.NewScriptOrigin(name, 1, 0)
script := engine.Compile(code, origin, nil)

Context

V8嵌入指南中的解释:

In V8, a context is an execution environment that allows separate, unrelated, JavaScript applications to run in a single instance of V8. You must explicitly specify the context in which you want any JavaScript code to be run.

在v8.go中,你可以从一个Engine实例中创建多个上下文。当你需要在某个上下文中运行一段JavaScript时,你需要调用Context.Scope()方法进入这个上下文,然后在回调函数中运行JavaScript。

context.Scope(func(cs v8.ContextScope){
	cs.Run(script)
})

上下文在V8中是可以嵌套的。所以v8.go中你可以这样做:

context.Scope(func(cs v8.ContextScope) {
	context2 := engine.NewContext(nil)
	context2.Scope(func(cs2 v8.ContextScope) {

	})
})

更多

请阅读v8_all_test.go以及samples目录下的示例代码。

Documentation

Index

Constants

View Source
const (
	PA_None       PropertyAttribute = 0
	PA_ReadOnly                     = 1 << 0
	PA_DontEnum                     = 1 << 1
	PA_DontDelete                   = 1 << 2
)
View Source
const (
	RF_None       RegExpFlags = 0
	RF_Global                 = 1
	RF_IgnoreCase             = 2
	RF_Multiline              = 4
)

Regular expression flag bits. They can be or'ed to enable a set of flags.

View Source
const (
	AC_DEFAULT               AccessControl = 0
	AC_ALL_CAN_READ                        = 1
	AC_ALL_CAN_WRITE                       = 1 << 1
	AC_PROHIBITS_OVERWRITING               = 1 << 2
)

Access control specifications.

Some accessors should be accessible across contexts. These accessors have an explicit access control parameter which specifies the kind of cross-context access that should be allowed.

Additionally, for security, accessors can prohibit overwriting by accessors defined in JavaScript. For objects that have such accessors either locally or in their prototype chain it is not possible to overwrite the accessor by using __defineGetter__ or __defineSetter__ from JavaScript code.

Variables

This section is empty.

Functions

func AppendJSON

func AppendJSON(dst []byte, value *Value) []byte

func ForceGC

func ForceGC()

func GetVersion

func GetVersion() string

func SetFlagsFromString

func SetFlagsFromString(cmd string)

func ToJSON

func ToJSON(value *Value) []byte

func UseDefaultArrayBufferAllocator

func UseDefaultArrayBufferAllocator()

Set default array buffer allocator to V8 for ArrayBuffer, ArrayBufferView, Int8Array... If you want to use your own allocator. You can implement it in C++ and invoke v8::SetArrayBufferAllocator by your self

Types

type AccessControl

type AccessControl int

type AccessorCallbackInfo

type AccessorCallbackInfo struct {
	// contains filtered or unexported fields
}

Property getter callback info

func (AccessorCallbackInfo) CurrentScope

func (ac AccessorCallbackInfo) CurrentScope() ContextScope

func (AccessorCallbackInfo) Data

func (ac AccessorCallbackInfo) Data() interface{}

func (AccessorCallbackInfo) Holder

func (ac AccessorCallbackInfo) Holder() *Object

func (*AccessorCallbackInfo) ReturnValue

func (ac *AccessorCallbackInfo) ReturnValue() ReturnValue

func (AccessorCallbackInfo) This

func (ac AccessorCallbackInfo) This() *Object

type AccessorGetterCallback

type AccessorGetterCallback func(name string, info AccessorCallbackInfo)

type AccessorSetterCallback

type AccessorSetterCallback func(name string, value *Value, info AccessorCallbackInfo)

type Array

type Array struct {
	*Object
}

An instance of the built-in array constructor (ECMA-262, 15.4.2).

func (*Array) Length

func (a *Array) Length() int

type Context

type Context struct {
	// contains filtered or unexported fields
}

A sandboxed execution context with its own set of built-in objects and functions.

func (Context) GetPrivateData

func (this Context) GetPrivateData() interface{}

func (*Context) Scope

func (c *Context) Scope(callback func(ContextScope))

func (*Context) SetPrivateData

func (this *Context) SetPrivateData(data interface{})

type ContextScope

type ContextScope struct {
	// contains filtered or unexported fields
}

func (ContextScope) Eval

func (cs ContextScope) Eval(code string) *Value

func (ContextScope) GetEngine

func (cs ContextScope) GetEngine() *Engine

func (ContextScope) GetPrivateData

func (cs ContextScope) GetPrivateData() interface{}

func (ContextScope) Global

func (cs ContextScope) Global() *Object

func (ContextScope) ParseJSON

func (cs ContextScope) ParseJSON(json string) *Value

func (ContextScope) Run

func (cs ContextScope) Run(s *Script) *Value

Runs the script returning the resulting value.

func (ContextScope) SetPrivateData

func (cs ContextScope) SetPrivateData(data interface{})

func (ContextScope) ThrowException

func (cs ContextScope) ThrowException(err string)

func (ContextScope) ThrowException2

func (cs ContextScope) ThrowException2(value *Value)

func (ContextScope) TryCatch

func (cs ContextScope) TryCatch(callback func()) error

func (ContextScope) TryCatchException

func (cs ContextScope) TryCatchException(callback func()) *Exception

type DynamicObject

type DynamicObject struct {
	Target     reflect.Value     // Target Go value.
	SpecFields []specField       // Special fields defined by 'js-field' struct tag.
	Properties []DynamicProperty // Dynamic properities.
}

DynamicObject used to handle dynamic property use case in JS.

func (*DynamicObject) DelDynamicProperty

func (dyObj *DynamicObject) DelDynamicProperty(name string)

Delete dynamic property.

func (*DynamicObject) GetDynamicProperty

func (dyObj *DynamicObject) GetDynamicProperty(name string) *Value

Get dynamic property.

func (*DynamicObject) GetSpecField

func (dyObj *DynamicObject) GetSpecField(name string) int

Get special field index.

func (*DynamicObject) SetDynamicProperty

func (dyObj *DynamicObject) SetDynamicProperty(name string, jsvalue *Value)

Set dynamic property. If the property not exists, it will be added.

type DynamicProperty

type DynamicProperty struct {
	Name  string // Property name.
	Value *Value // JS value.
}

Dynamic object property.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Represents an isolated instance of the V8 engine. Objects from one engine must not be used in other engine. Not thred safe!

func NewEngine

func NewEngine() *Engine

func (*Engine) AddMessageListener

func (engine *Engine) AddMessageListener(callback MessageCallback) int64

func (*Engine) Compile

func (e *Engine) Compile(code []byte, origin *ScriptOrigin) *Script

Compiles the specified script (context-independent). 'data' is the Pre-parsing data, as obtained by PreCompile() using pre_data speeds compilation if it's done multiple times.

func (*Engine) False

func (e *Engine) False() *Value

func (Engine) GetPrivateData

func (this Engine) GetPrivateData() interface{}

func (*Engine) GoValueToJsValue

func (engine *Engine) GoValueToJsValue(value reflect.Value) *Value

func (*Engine) NewArray

func (e *Engine) NewArray(length int) *Value

func (*Engine) NewBoolean

func (e *Engine) NewBoolean(value bool) *Value

func (*Engine) NewContext

func (e *Engine) NewContext(globalTemplate *ObjectTemplate) *Context

func (*Engine) NewDate

func (e *Engine) NewDate(value time.Time) *Value

func (*Engine) NewError

func (e *Engine) NewError(message string) *Value

func (*Engine) NewExternal

func (e *Engine) NewExternal(value interface{}) *External

func (*Engine) NewFunction

func (e *Engine) NewFunction(callback FunctionCallback, data interface{}) *Function

func (*Engine) NewFunctionTemplate

func (e *Engine) NewFunctionTemplate(callback FunctionCallback, data interface{}) *FunctionTemplate

func (*Engine) NewInstanceOf

func (e *Engine) NewInstanceOf(ot *ObjectTemplate) *Value

func (*Engine) NewInteger

func (e *Engine) NewInteger(value int64) *Value

func (*Engine) NewNumber

func (e *Engine) NewNumber(value float64) *Value

func (*Engine) NewObject

func (e *Engine) NewObject() *Value

func (*Engine) NewObjectTemplate

func (e *Engine) NewObjectTemplate() *ObjectTemplate

func (*Engine) NewRangeError

func (e *Engine) NewRangeError(message string) *Value

func (*Engine) NewReferenceError

func (e *Engine) NewReferenceError(message string) *Value

func (*Engine) NewRegExp

func (e *Engine) NewRegExp(pattern string, flags RegExpFlags) *Value

Creates a regular expression from the given pattern string and the flags bit field. May throw a JavaScript exception as described in ECMA-262, 15.10.4.1.

For example,

NewRegExp("foo", RF_Global | RF_Multiline)

is equivalent to evaluating "/foo/gm".

func (*Engine) NewScriptOrigin

func (e *Engine) NewScriptOrigin(name string, lineOffset, columnOffset int) *ScriptOrigin

func (*Engine) NewString

func (e *Engine) NewString(value string) *Value

func (*Engine) NewSyntaxError

func (e *Engine) NewSyntaxError(message string) *Value

func (*Engine) NewTypeError

func (e *Engine) NewTypeError(message string) *Value

func (*Engine) Null

func (e *Engine) Null() *Value

func (*Engine) RemoveMessageListener

func (engine *Engine) RemoveMessageListener(id int64)

func (*Engine) SetCaptureStackTraceForUncaughtExceptions

func (engine *Engine) SetCaptureStackTraceForUncaughtExceptions(capture bool, frameLimit int)

func (*Engine) SetJsValueToGo

func (engine *Engine) SetJsValueToGo(field reflect.Value, jsvalue *Value)

func (*Engine) SetPrivateData

func (this *Engine) SetPrivateData(data interface{})

func (*Engine) True

func (e *Engine) True() *Value

func (*Engine) Undefined

func (e *Engine) Undefined() *Value

type Exception

type Exception struct {
	*Value
	*Message
}

type External

type External struct {
	*Value
	// contains filtered or unexported fields
}

func (*External) GetValue

func (ex *External) GetValue() interface{}

type Function

type Function struct {
	*Object
	// contains filtered or unexported fields
}

A JavaScript function object (ECMA-262, 15.3).

func (*Function) Call

func (f *Function) Call(args ...*Value) *Value

func (*Function) NewInstance

func (f *Function) NewInstance(args ...*Value) *Value

type FunctionCallback

type FunctionCallback func(FunctionCallbackInfo)

type FunctionCallbackInfo

type FunctionCallbackInfo struct {
	// contains filtered or unexported fields
}

Function callback info

func (FunctionCallbackInfo) Callee

func (fc FunctionCallbackInfo) Callee() *Function

func (FunctionCallbackInfo) CurrentScope

func (fc FunctionCallbackInfo) CurrentScope() ContextScope

func (FunctionCallbackInfo) Data

func (fc FunctionCallbackInfo) Data() interface{}

func (FunctionCallbackInfo) Get

func (fc FunctionCallbackInfo) Get(i int) *Value

func (FunctionCallbackInfo) Holder

func (fc FunctionCallbackInfo) Holder() *Object

func (FunctionCallbackInfo) Length

func (fc FunctionCallbackInfo) Length() int

func (*FunctionCallbackInfo) ReturnValue

func (fc *FunctionCallbackInfo) ReturnValue() ReturnValue

func (FunctionCallbackInfo) This

func (fc FunctionCallbackInfo) This() *Object

type FunctionTemplate

type FunctionTemplate struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*FunctionTemplate) Dispose

func (ft *FunctionTemplate) Dispose()

func (*FunctionTemplate) InstanceTemplate

func (ft *FunctionTemplate) InstanceTemplate() *ObjectTemplate

func (*FunctionTemplate) NewFunction

func (ft *FunctionTemplate) NewFunction() *Value

func (*FunctionTemplate) SetClassName

func (ft *FunctionTemplate) SetClassName(name string)

type IndexedPropertyDeleterCallback

type IndexedPropertyDeleterCallback func(uint32, PropertyCallbackInfo)

type IndexedPropertyEnumeratorCallback

type IndexedPropertyEnumeratorCallback func(PropertyCallbackInfo)

type IndexedPropertyGetterCallback

type IndexedPropertyGetterCallback func(uint32, PropertyCallbackInfo)

type IndexedPropertyQueryCallback

type IndexedPropertyQueryCallback func(uint32, PropertyCallbackInfo)

type IndexedPropertySetterCallback

type IndexedPropertySetterCallback func(uint32, *Value, PropertyCallbackInfo)

type Message

type Message struct {
	Message            string
	SourceLine         string
	ScriptResourceName string
	StackTrace         StackTrace
	Line               int
	StartPosition      int
	EndPosition        int
	StartColumn        int
	EndColumn          int
}

func (*Message) Error

func (m *Message) Error() string

type MessageCallback

type MessageCallback func(message *Message)

type NamedPropertyDeleterCallback

type NamedPropertyDeleterCallback func(string, PropertyCallbackInfo)

type NamedPropertyEnumeratorCallback

type NamedPropertyEnumeratorCallback func(PropertyCallbackInfo)

type NamedPropertyGetterCallback

type NamedPropertyGetterCallback func(string, PropertyCallbackInfo)

type NamedPropertyQueryCallback

type NamedPropertyQueryCallback func(string, PropertyCallbackInfo)

type NamedPropertySetterCallback

type NamedPropertySetterCallback func(string, *Value, PropertyCallbackInfo)

type Object

type Object struct {
	*Value
	// contains filtered or unexported fields
}

A JavaScript object (ECMA-262, 4.3.3)

func (*Object) DeleteElement

func (o *Object) DeleteElement(index int) bool

func (*Object) DeleteProperty

func (o *Object) DeleteProperty(key string) bool

func (*Object) ForceDeleteProperty

func (o *Object) ForceDeleteProperty(key string) bool

Delete a property on this object bypassing interceptors and ignoring dont-delete attributes.

func (*Object) ForceSetProperty

func (o *Object) ForceSetProperty(key string, value *Value, attribs PropertyAttribute) bool

Sets a local property on this object bypassing interceptors and overriding accessors or read-only properties.

Note that if the object has an interceptor the property will be set locally, but since the interceptor takes precedence the local property will only be returned if the interceptor doesn't return a value.

Note also that this only works for named properties.

func (*Object) GetElement

func (o *Object) GetElement(index int) *Value

func (*Object) GetInternalField

func (o *Object) GetInternalField(index int) interface{}

func (*Object) GetOwnPropertyNames

func (o *Object) GetOwnPropertyNames() *Array

This function has the same functionality as GetPropertyNames but the returned array doesn't contain the names of properties from prototype objects.

func (*Object) GetProperty

func (o *Object) GetProperty(key string) *Value

func (*Object) GetPropertyAttributes

func (o *Object) GetPropertyAttributes(key string) PropertyAttribute

func (*Object) GetPropertyNames

func (o *Object) GetPropertyNames() *Array

Returns an array containing the names of the enumerable properties of this object, including properties from prototype objects. The array returned by this method contains the same values as would be enumerated by a for-in statement over this object.

func (*Object) GetPrototype

func (o *Object) GetPrototype() *Object

Get the prototype object. This does not skip objects marked to be skipped by __proto__ and it does not consult the security handler.

func (*Object) HasElement

func (o *Object) HasElement(index int) bool

func (*Object) HasProperty

func (o *Object) HasProperty(key string) bool

func (*Object) InternalFieldCount

func (o *Object) InternalFieldCount() int

func (*Object) SetAccessor

func (o *Object) SetAccessor(
	key string,
	getter AccessorGetterCallback,
	setter AccessorSetterCallback,
	data interface{},
	attribs PropertyAttribute,
)

func (*Object) SetElement

func (o *Object) SetElement(index int, value *Value) bool

func (*Object) SetInternalField

func (o *Object) SetInternalField(index int, value interface{})

func (*Object) SetProperty

func (o *Object) SetProperty(key string, value *Value, attribs PropertyAttribute) bool

func (*Object) SetPrototype

func (o *Object) SetPrototype(proto *Object) bool

Set the prototype object. This does not skip objects marked to be skipped by __proto__ and it does not consult the security handler.

type ObjectTemplate

type ObjectTemplate struct {
	sync.Mutex
	// contains filtered or unexported fields
}

func (*ObjectTemplate) Bind

func (template *ObjectTemplate) Bind(typeName string, target interface{}) error

Fast bind Go type or function to JS. Note, The function template and object template created in fast bind internal are never destroyed. The JS class map to Go type use a internal field to reference a Go object when it instanced. All of the internal field keep reference by engine. So, may be you don't like to create too many instance of them.

func (*ObjectTemplate) Dispose

func (ot *ObjectTemplate) Dispose()

func (*ObjectTemplate) InternalFieldCount

func (ot *ObjectTemplate) InternalFieldCount() int

func (*ObjectTemplate) Plugin

func (ot *ObjectTemplate) Plugin(pluginInit unsafe.Pointer)

func (*ObjectTemplate) SetAccessor

func (ot *ObjectTemplate) SetAccessor(
	key string,
	getter AccessorGetterCallback,
	setter AccessorSetterCallback,
	data interface{},
	attribs PropertyAttribute,
)

func (*ObjectTemplate) SetIndexedPropertyHandler

func (ot *ObjectTemplate) SetIndexedPropertyHandler(
	getter IndexedPropertyGetterCallback,
	setter IndexedPropertySetterCallback,
	query IndexedPropertyQueryCallback,
	deleter IndexedPropertyDeleterCallback,
	enumerator IndexedPropertyEnumeratorCallback,
	data interface{},
)

func (*ObjectTemplate) SetInternalFieldCount

func (ot *ObjectTemplate) SetInternalFieldCount(count int)

func (*ObjectTemplate) SetNamedPropertyHandler

func (ot *ObjectTemplate) SetNamedPropertyHandler(
	getter NamedPropertyGetterCallback,
	setter NamedPropertySetterCallback,
	query NamedPropertyQueryCallback,
	deleter NamedPropertyDeleterCallback,
	enumerator NamedPropertyEnumeratorCallback,
	data interface{},
)

func (*ObjectTemplate) SetProperty

func (ot *ObjectTemplate) SetProperty(key string, value *Value, attribs PropertyAttribute)

func (*ObjectTemplate) WrapObject

func (ot *ObjectTemplate) WrapObject(value *Value)

type PropertyAttribute

type PropertyAttribute int

type PropertyCallbackInfo

type PropertyCallbackInfo struct {
	// contains filtered or unexported fields
}

func (PropertyCallbackInfo) CurrentScope

func (p PropertyCallbackInfo) CurrentScope() ContextScope

func (PropertyCallbackInfo) Data

func (p PropertyCallbackInfo) Data() interface{}

func (PropertyCallbackInfo) Holder

func (p PropertyCallbackInfo) Holder() *Object

func (PropertyCallbackInfo) ReturnValue

func (p PropertyCallbackInfo) ReturnValue() ReturnValue

func (PropertyCallbackInfo) This

func (p PropertyCallbackInfo) This() *Object

type RegExp

type RegExp struct {
	*Object
	// contains filtered or unexported fields
}

func (*RegExp) Flags

func (r *RegExp) Flags() RegExpFlags

Returns the flags bit field.

func (*RegExp) Pattern

func (r *RegExp) Pattern() string

Returns the value of the source property: a string representing the regular expression.

type RegExpFlags

type RegExpFlags int

type ReturnValue

type ReturnValue struct {
	// contains filtered or unexported fields
}

Function and property return value

func (ReturnValue) Set

func (rv ReturnValue) Set(value *Value)

func (ReturnValue) SetBoolean

func (rv ReturnValue) SetBoolean(value bool)

func (ReturnValue) SetInt32

func (rv ReturnValue) SetInt32(value int32)

func (ReturnValue) SetNull

func (rv ReturnValue) SetNull()

func (ReturnValue) SetNumber

func (rv ReturnValue) SetNumber(value float64)

func (ReturnValue) SetString

func (rv ReturnValue) SetString(value string)

func (ReturnValue) SetUint32

func (rv ReturnValue) SetUint32(value uint32)

func (ReturnValue) SetUndefined

func (rv ReturnValue) SetUndefined()

type Script

type Script struct {
	// contains filtered or unexported fields
}

A compiled JavaScript script.

type ScriptOrigin

type ScriptOrigin struct {
	Name         string
	LineOffset   int
	ColumnOffset int
}

The origin, within a file, of a script.

type StackFrame

type StackFrame struct {
	Line                  int
	Column                int
	ScriptId              int
	ScriptName            string
	ScriptNameOrSourceURL string
	FunctionName          string
	IsEval                bool
	IsConstructor         bool
}

type StackTrace

type StackTrace []*StackFrame

func (StackTrace) String

func (s StackTrace) String() string

type StackTraceOptions

type StackTraceOptions uint

type Value

type Value struct {
	// contains filtered or unexported fields
}

The superclass of all JavaScript values and objects.

func (*Value) IsArray

func (v *Value) IsArray() bool

func (*Value) IsBoolean

func (v *Value) IsBoolean() bool

func (*Value) IsBooleanObject

func (v *Value) IsBooleanObject() bool

func (*Value) IsDate

func (v *Value) IsDate() bool

func (*Value) IsExternal

func (v *Value) IsExternal() bool

func (*Value) IsFalse

func (v *Value) IsFalse() bool

func (*Value) IsFunction

func (v *Value) IsFunction() bool

func (*Value) IsInt32

func (v *Value) IsInt32() bool

func (*Value) IsNativeError

func (v *Value) IsNativeError() bool

func (*Value) IsNull

func (v *Value) IsNull() bool

func (*Value) IsNumber

func (v *Value) IsNumber() bool

func (*Value) IsNumberObject

func (v *Value) IsNumberObject() bool

func (*Value) IsObject

func (v *Value) IsObject() bool

func (*Value) IsRegExp

func (v *Value) IsRegExp() bool

func (*Value) IsString

func (v *Value) IsString() bool

func (*Value) IsStringObject

func (v *Value) IsStringObject() bool

func (*Value) IsTrue

func (v *Value) IsTrue() bool

func (*Value) IsUint32

func (v *Value) IsUint32() bool

func (*Value) IsUndefined

func (v *Value) IsUndefined() bool

func (*Value) String

func (v *Value) String() string

func (*Value) ToArray

func (v *Value) ToArray() *Array

func (*Value) ToBoolean

func (v *Value) ToBoolean() bool

func (*Value) ToExternal

func (v *Value) ToExternal() *External

func (*Value) ToFunction

func (v *Value) ToFunction() *Function

func (*Value) ToInt32

func (v *Value) ToInt32() int32

func (*Value) ToInteger

func (v *Value) ToInteger() int64

func (*Value) ToNumber

func (v *Value) ToNumber() float64

func (*Value) ToObject

func (v *Value) ToObject() *Object

func (*Value) ToRegExp

func (v *Value) ToRegExp() *RegExp

func (*Value) ToString

func (v *Value) ToString() string

func (*Value) ToTime

func (v *Value) ToTime() time.Time

func (*Value) ToUint32

func (v *Value) ToUint32() uint32

Directories

Path Synopsis
samples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL