jz

package module
v0.0.0-...-59f3579 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

jz

Go Reference Go Report Card

A utility package that makes JavaScript bindings in WASM-compiled Go code feel like native Go code. Write idiomatic Go code that seamlessly interacts with browser JavaScript APIs.

I hope this package becomes obsolete soon when WASI becomes natively supported in browsers, eliminating the need for these JavaScript bindings altogether.

Features

  • Promise Handling: Await JavaScript Promises with Go's context support
  • HTTP Client: Use net/http with fetch API through a FetchTransport
  • Stream I/O: Convert JavaScript ReadableStreams to io.Reader
  • Type Conversion: Unmarshal JavaScript types to Go.

Installation

go get github.com/lesomnus/jz

Usage

This library is designed for Go code compiled to WebAssembly targeting the browser (GOOS=js GOARCH=wasm).

Promise Handling

Await JavaScript Promises with Go's familiar error handling:

import "github.com/lesomnus/jz"

// Await a Promise.
result, err := jz.Await(jsPromise)
if err != nil {
	// Handle rejection.
}

// Await with context support.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

result, err := jz.AwaitContext(ctx, jsPromise)
if err != nil {
	// Handle rejection or timeout.
}

// Create a Promise from Go code.
promise := jz.Promise(func() (any, any) {
	result, err := doSomething()
	return result, err
})
HTTP with Fetch API

Use the standard net/http package with the browser's fetch API:

import (
	"net/http"
	"github.com/lesomnus/jz"
)

client := &http.Client{
	Transport: jz.FetchTransport{},
}

res, err := client.Get("https://api.example.com/data")
if err != nil {
	// Handle error.
}
defer res.Body.Close()

body, err := io.ReadAll(res.Body)
Stream Reading

Convert JavaScript ReadableStreams to Go's io.Reader:

// jsStream is a JavaScript ReadableStream.
reader, err := jz.NewReader(jsStream)
if err != nil {
	// Handle error
}
defer reader.Close()

// Use like any io.Reader.
data, err := io.ReadAll(reader)
Type Conversion

Unmarshal JavaScript objects to Go structs:

type User struct {
	Name  string
	Email string
	Age   int
}

var user User
err := jz.Unmarshal(jsValue, &user)
if err != nil {
	// Handle error.
}
Utility Functions
// Convert JavaScript values to readable strings.
str := jz.Stringify(jsValue)

// Access nested properties like optional chaining.
window := js.Global()
fetch := jz.GetX(window, "fetch")
json := jz.GetX(window, "JSON", "stringify")

Testing

For full tests, including FetchTransport, you need an HTTP server to target.

$ go run ./internal/httptest

Then run tests with wasm/js. The required environment variables are defined at ./scripts/setup.sh.

$ source ./scripts/setup.sh
$ go test

Documentation

Rendered for js/wasm

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Await

func Await(p js.Value) (js.Value, error)

Await waits for a JavaScript Promise to resolve and returns its result. If the Promise is rejected, an error is returned.

func AwaitContext

func AwaitContext(ctx context.Context, p js.Value) (js.Value, error)

AwaitContext waits for a JavaScript Promise to resolve with context support. The wait can be cancelled via the provided context.

func BytesToGo

func BytesToGo(v js.Value) []byte

BytesToGo converts a JavaScript Uint8Array to a Go byte slice.

func BytesToJs

func BytesToJs(v []byte) js.Value

BytesToJs converts a Go byte slice to a JavaScript Uint8Array.

func Get

func Get(v js.Value, ps ...string) (js.Value, bool)

Get navigates through nested JavaScript object properties. Returns the final value and true if all properties exist, or js.Undefined and false otherwise.

func GetX

func GetX(v js.Value, ps ...string) js.Value

GetX navigates through nested JavaScript object properties without checking existence. Returns js.Undefined if any property in the path doesn't exist.

func NewError

func NewError(msg string) js.Value

func NewReadableStream

func NewReadableStream(r io.ReadCloser) js.Value

func NewReader

func NewReader(v js.Value) (io.ReadCloser, error)

func Object

func Object(v map[string]any) js.Value

Object converts a Go map to a JavaScript object.

func Promise

func Promise(f func() (any, any)) js.Value

Promise creates a JavaScript Promise from a Go function. The function f should return a result value and an error. If the error is not nil, the Promise will be rejected.

Note: Unlike a JavaScript `new Promise((resolve, reject) => { ... })` executor, the function you pass is not run synchronously during construction. It is deferred and executed in a separate goroutine after the current call returns. Therefore, any side effects or panics inside the function will not be observable in the immediate calling context.

func Reject

func Reject(v js.Value) js.Value

Reject creates a Promise that rejects with the given value.

func Resolve

func Resolve(v js.Value) js.Value

Resolve creates a Promise that resolves to the given value.

func Stringify

func Stringify(jv js.Value) string

Stringify converts a value to its string representation.

func Unmarshal

func Unmarshal(data js.Value, v any) error

Unmarshal converts a JavaScript value to a Go value. The target v must be a non-nil pointer. It supports struct tags "js" for field mapping.

Types

type FetchTransport

type FetchTransport struct{}

func (FetchTransport) RoundTrip

func (t FetchTransport) RoundTrip(req *http.Request) (*http.Response, error)

type RejectedError

type RejectedError struct {
	Value js.Value
}

func (RejectedError) Error

func (e RejectedError) Error() string

type Scope

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

func GlobalScope

func GlobalScope() *Scope

GlobalScope returns the global Scope instance that can be used to manage JavaScript function lifecycles and wait for their completion.

func (*Scope) Await

func (s *Scope) Await(p js.Value) (js.Value, error)

func (*Scope) AwaitContext

func (s *Scope) AwaitContext(ctx context.Context, p js.Value) (js.Value, error)

func (*Scope) FuncOf

func (s *Scope) FuncOf(f func(this js.Value, args []js.Value) any) js.Func

func (*Scope) Promise

func (s *Scope) Promise(f func() (any, any)) js.Value

func (*Scope) Wait

func (s *Scope) Wait()

Directories

Path Synopsis
internal
httptest command

Jump to

Keyboard shortcuts

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