vert

package module
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 29, 2022 License: MIT Imports: 3 Imported by: 0

README

vert

Package vert provides WebAssembly interop between Go and JS values.

Differences from norunners/vert

  • removed vert.Value type so that the package is compatible with go1.18 (js.Wrapper was removed)
  • changed signature of func(vert.Value) AssignTo(any) to func AssignTo(js.Value, any)

Install

GOOS=js GOARCH=wasm go get github.com/jrs526/vert

Examples

Hello World!

Below is a trivial string value interop.

package main

import "github.com/jrs526/vert/v2"

func main() {
	v := vert.ValueOf("Hello World!")
	// Use v as a JS value.

	s := ""
	vert.AssignTo(v, &s)
	// Use s as a Go value.
}
Structs & Objects

Go structs and JS objects interop seamlessly.

package main

import "github.com/jrs526/vert/v2"

type Data struct {
	Message string
}

func main() {
	v := vert.ValueOf(Data{
		Message: "Hello World!",
	})
	// e.g. {"Message": "Hello World!"}

	d := &Data{}
	vert.AssignTo(v, d)
}
Tagged Struct Fields

Tagged struct fields allow defined JS field names.

package main

import "github.com/jrs526/vert/v2"

type Data struct {
	Message string `js:"msg"`
}

func main() {
	v := vert.ValueOf(Data{
		Message: "Hello World!",
	})
	// The defined JS tag names the field.
	// e.g. {"msg": "Hello World!"}

	d := &Data{}
	vert.AssignTo(v, d)
}

Error Handling

AssignTo returns an error value.

package main

import "github.com/jrs526/vert/v2"

type Data struct {
	Message string
}

func main() {
	v := vert.ValueOf("Hello World!")

	d := &Data{}
	if err := vert.AssignTo(v, d); err != nil {
		// Handle error.
	}
}

Why?

Package syscall/js, of the Go standard library, has limited interop support between Go and JS values.

  1. The function js.ValueOf will not accept struct types. The result panics with ValueOf: invalid value.
  2. The type js.Value. does not support an Interface or assignment method for non-basic Go values. However, the methods Bool, Int, Float and String support basic Go values.

Package vert leverages and extends syscall/js to accommodate these shortcomings.

License

Documentation

Rendered for js/wasm

Overview

Package vert provides WebAssembly interop between Go and JS values.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AssignTo

func AssignTo(jv js.Value, i interface{}) error

AssignTo assigns a JS value to a Go pointer. Returns an error on invalid assignments.

func ValueOf

func ValueOf(i interface{}) js.Value

ValueOf returns the Go value as a new value.

Types

type InvalidAssignmentError

type InvalidAssignmentError struct {
	Type js.Type
	Kind reflect.Kind
	// contains filtered or unexported fields
}

func (*InvalidAssignmentError) Error

func (e *InvalidAssignmentError) Error() string

Jump to

Keyboard shortcuts

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