Documentation
¶
Overview ¶
Package jsgo provides complete Go↔JavaScript interoperability for WebAssembly with advanced features beyond standard library capabilities:
Features: - Bidirectional type conversion with struct tags (`jsgo:"field"`) - Export any Go function to JavaScript - Create JS classes from Go structs with inheritance - Automatic cycle detection and error handling - Pooled memory management for high-performance - Extended type support (time.Time, big.Int)
Core Concepts ¶
Function Export: Export Go functions to JS with any signature using FuncOfAny:
jsgo.FuncOfAny(func(x int) string { ... })
Class System: Create JS classes from Go structs with inheritance:
type User struct { Base `jsgo:",extends=BaseClass"` Name string `jsgo:"username"` }
Type Conversion: Convert complex types bidirectionally:
jsgo.Marshal(userStruct) → JS object jsgo.Unmarshal(jsObj, &userStruct)
Security ¶
- Validate all JS callback arguments - Never expose unguarded system functions - Use Release() for sensitive resources
# Struct Tags `jsgo:"-"` // Ignore field `jsgo:"fieldName"` // Custom property name `jsgo:",omitempty"` // Omit if empty `jsgo:",extends=BaseClass"` // Inheritance
Index ¶
- func Bytes(b []byte) js.Value
- func BytesN(b []byte) (js.Value, int)
- func CopyObject(dst, src js.Value) (err error)
- func ExportGoType[T any](constructor any) (release func(), err error)
- func ExportGoTypeWithName[T any](constructor any, name string) (release func(), err error)
- func FuncOf(f func(this js.Value, jsArgs []js.Value) interface{}) js.Func
- func FuncOfAny(f any) js.Func
- func IsArray(v js.Value) bool
- func IsObject(v js.Value) bool
- func MakeArray(len int, cap int) js.Value
- func MakeArrayNoBuffer(len int) js.Value
- func MakeBytes(len int, cap int) js.Value
- func MakeBytesNoBuffer(len int) js.Value
- func Marshal(goVal any) (js.Value, error)
- func MarshalInto(jsVal js.Value, goVal any) error
- func New(name string, args ...any) js.Value
- func NewObject() js.Value
- func ObjectKeys(v js.Value) []string
- func PrototypeOf(obj js.Value) js.Value
- func Throw(err error) js.Value
- func Type(name string) js.Value
- func TypeJSParallel[T any]() js.Type
- func Unmarshal(jsVal js.Value, goVal any) error
- type Class
- type ConstructorConfig
- type Marshaler
- type MarshalerInto
- type Unmarshaler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Bytes ¶
Bytes efficiently converts Go byte slices to JavaScript Uint8Array. Panics if the copy is incomplete to prevent subtle data bugs.
For partial copies, use BytesN and check the returned count.
func CopyObject ¶
func ExportGoType ¶
ExportGoType exports a Go type as a JavaScript class with automatic resource management. Returns a cleanup function that should be called when the class is no longer needed.
func ExportGoTypeWithName ¶
ExportGoTypeWithName exports a Go type with a custom JavaScript class name. Useful for renaming types in the JS environment.
func FuncOf ¶
FuncOf provides a safer and more ergonomic alternative to js.FuncOf with automatic error handling. Converts Go errors to JS exceptions automatically. Return types are not limited unlike js.FuncOf
func FuncOfAny ¶
FuncOfAny wraps Go functions into JS functions with automatic type conversion. Supports variadic functions and handles error propagation.
Example:
jsFunc := FuncOfAny(func(x int) int { return x*2 }) js.Global().Set("double", jsFunc) defer jsFunc.Release()
Note: Argument modifications won't affect JS side and returned values are copies.
Example ¶
Function export and invocation
// Export Go function double := jsgo.FuncOfAny(func(x int) int { return x * 2 }) defer double.Release() js.Global().Set("double", double) // JavaScript equivalent: // console.log(double(4)) // Output: 8
func MakeArrayNoBuffer ¶
func MakeBytes ¶
MakeBytes creates a byte buffer with both length and capacity Underlying storage uses ArrayBuffer for optimal memory layout
Example:
buf := MakeBytes(1024, 4096) // 1KB view, 4KB capacity
func MakeBytesNoBuffer ¶
func Marshal ¶
Marshal converts Go values to JavaScript values with special handling for: - time.Time → JS Date - []byte → Uint8Array - big.Int → JS BigInt - Functions → JS callbacks
Example:
type User struct { Name string `jsgo:"username"` } u := &User{Name: "Alice"} jsVal, err := Marshal(u) // Returns JS object {username: "Alice"}
Gotchas: - Cyclic structures return error - Channels are not supported
Example ¶
Marshal example (Go → JS conversion)
type User struct { Name string `jsgo:"username"` Age int `jsgo:"userAge"` } u := User{Name: "Alice", Age: 30} jsVal, _ := jsgo.Marshal(u) fmt.Println(jsVal.Get("username").String())
Output: Alice
func MarshalInto ¶
MarshalInto marshals a Go value into an existing JavaScript reference type (Object). More efficient than Marshal for repeated operations as it reuses JS containers instead of creating new ones.
Parameters:
- jsVal: Must be a JS reference type (Object, Array, TypedArray)
- goVal: Go value to marshal (struct, map, slice, etc)
Returns:
- error if marshaling fails (cyclic ref, unsupported type, etc)
Example:
jsObj := js.Global().Get("Object").New() err := MarshalInto(jsObj, myStruct) jsObj.Call("someMethod")
Notes:
- Prefer for hot paths where JS object reuse matters
- Does not clear existing properties
func New ¶
New creates a JavaScript object using the specified constructor. Equivalent to `new ConstructorName(...args)` in JavaScript.
Example:
arr := jsgo.New("Array", 10) // Creates new Array(10)
func ObjectKeys ¶
ObjectKeys returns the enumerable own properties of a JS object.
func Throw ¶
Throw converts Go errors to JS exceptions. Use in function callbacks to propagate errors properly to JS.
Example:
js.FuncOf(func(this js.Value, args []js.Value) any { result, err := riskyOperation() if err != nil { return Throw(err) } return result })
func TypeJSParallel ¶
func Unmarshal ¶
Unmarshal populates Go values from JavaScript values with strict type checking.
similar to JSON unmarshaling.
Requires a pointer to writable memory.
Handles:
- JS Date → time.Time (UTC) - JS BigInt → int64/uint64/big.Int - JS Array → Go slice/array
Example:
var user struct{Name string `jsgo:"username"`} err := Unmarshal(jsObject, &user)
Gotchas: - Numeric overflow returns error - JS null converts to Go zero values
Implement to encoding.TextUnmarshaler to support complex key types when unmarshaling JS objects to Go maps.
Example ¶
Unmarshal example (JS → Go conversion)
type User struct { Name string `jsgo:"username"` Age int `jsgo:"userAge"` } jsObj := js.Global().Get("Object").New() jsObj.Set("username", "Bob") jsObj.Set("userAge", 25) var result User jsgo.Unmarshal(jsObj, &result) fmt.Println(result.Name)
Output: Bob
Types ¶
type Class ¶
Class represents a JavaScript class with its constructor and methods. Use Release() to clean up resources when done
func TypeFor ¶
TypeFor creates a Go type as a JavaScript class with proper inheritance support.
Parameters:
- T: Go type to export (must be struct, array types, or map)
- constructor: Either:
- nil for default constructor
- Constructor function (func(...) (T, [error])) // optional error
- ConstructorConfig for advanced control
Returns:
- error: Initialization error if any
- release: Cleanup function to free JS resources
- class: type as a js.Value
Features: - Inheritance via embedded struct tags: `jsgo:",extends=ParentClass"` - Custom super constructor arguments via ConstructorConfig.SuperArgs - Automatic resource management - Method export for exported Go methods
Example:
type MyClass struct { BaseClass `jsgo:",extends=BaseJSClass"` // can be js.Value or formerly exported types } func NewMyClass(arg string) (*MyClass, error) { ... } // Export with custom super args cfg := ConstructorConfig{ Fn: NewMyClass, SuperArgs: func(args []js.Value) []js.Value { return []js.Value{js.ValueOf("processed")} }, } class, release, err := TypeFor[MyClass](cfg)
Example ¶
Class creation and inheritance
type Base struct { ID string `jsgo:"id"` } type User struct { Base `jsgo:",extends=BaseClass"` Username string `jsgo:"username"` } // Export as JS class class, _ := jsgo.TypeFor[User](jsgo.ConstructorConfig{ Fn: func(id, name string) *User { return &User{Base: Base{ID: id}, Username: name} }, }) defer class.Release() // JavaScript equivalent: // const user = new User("123", "alice"); // console.log(user.id, user.username); // 123, alice
type ConstructorConfig ¶
type ConstructorConfig struct { // Constructor function that returns an instance of the type Fn interface{} // SuperArgs transforms arguments before passing to parent constructor. // If nil, all arguments are passed through. SuperArgs func([]js.Value) []js.Value }
ConstructorConfig defines configuration options for class constructors
type Marshaler ¶
Marshaler is the interface implemented by types that can convert themselves to JavaScript values. Use for custom serialization logic.
Example:
type CustomID string func (id CustomID) MarshalJS() (js.Value, error) { return js.ValueOf("ID:"+string(id)), nil }
type MarshalerInto ¶
MarshalerInto allows certain types(types have jsgo.TypeJSParallel[T]() == js.TypeObject) to marshal into existing JS values. Implementing this interface provides both MarshalJS and MarshalIntoJS capabilities.
Example:
type MySophisticatedType struct { myPrivateField int } func (m MySophisticatedType) MarshalIntoJS(v js.Value) error { v.Set("exposedField", m.myPrivateField) return nil }
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can decode themselves from JavaScript values. Use for custom validation/parsing.
Example:
type Account struct{ Balance float64 } func (a *Account) UnmarshalJS(v js.Value) error { if v.Type() != js.TypeObject { return errors.New("must be object") } a.Balance = v.Get("balance").Float() return nil }