Giter VIP home page Giter VIP logo

wasm_go_package's Introduction

wasm_go_package

go语言函数编译为webassemblyjs调用

1.编写go函数

package main
import (
	_ "embed"
	"errors"
	"fmt"
)

func add(args []float64) any {
	if len(args) == 0 {
		return errors.New("参数不能为空!")
	}
	return args[0] + args[1]
}

func main() {
	fmt.Println(add([]float64{1, 2}))
}

2.改造代码

// 1.新增编译头文件(固定写法)
//go:build js && wasm
// +build js,wasm

package main

import (
	"errors"
	// 2.引入go webassembly编译库
	"syscall/js"
)

// 3.改造go函数
func add(this js.Value, args []js.Value) any {
	if len(args) == 0 {
		return errors.New("参数不能为空!")
	}
	x := args[0].Float()
	y := args[1].Float()
	return x+y
}

// 4.挂载全局变量,并且挂起
func main() {
	js.Global().Set("add", js.FuncOf(add))
	// 阻塞挂起
	<-make(chan any)
}

3.开始编译

GOOS=js GOARCH=wasm go build -o test.wasm test/main.go

执行上述命令之后,在当前目录下会生成test.wasm代码,并且会在go安装目录下的misc/wasm文件夹生成wasm_exec.htmlwasm_exec.js等代码。

enjoy:)

wasm_go_package's People

Contributors

keekuun avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.