Skip to content

Instantly share code, notes, and snippets.

@a-x-
Last active June 3, 2019 20:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-x-/c6b8f2b25e3dbd12fbae0a3a64c1fa4a to your computer and use it in GitHub Desktop.
Save a-x-/c6b8f2b25e3dbd12fbae0a3a64c1fa4a to your computer and use it in GitHub Desktop.
golang wasm. go <-> js interlop
<html>
<head>
<meta charset="utf-8">
<script src="wasm_exec.js"></script>
<script>
const go = new Go();
WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
go.run(result.instance);
console.log(Template('123', "Цифры из этого смс никому нельзя сообщать. Для входа в приложение Рокетбанка введите код {{ index . 0 }}"));
});
</script>
</head>
<body></body>
</html>
package main
// import "fmt"
import "syscall/js"
import (
"bytes"
"html/template"
)
func Add(i []js.Value) {
js.Global().Set("output", js.ValueOf(i[0].Int()+i[1].Int()))
println(js.ValueOf(i[0].Int() + i[1].Int()).String())
}
func Subtract(i []js.Value) {
js.Global().Set("output", js.ValueOf(i[0].Int()-i[1].Int()))
println(js.ValueOf(i[0].Int() - i[1].Int()).String())
}
func registerCallbacks() {
js.Global().Set("Add", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
Add(args)
return true
}))
js.Global().Set("Subtract", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
Subtract(args)
return true
}))
js.Global().Set("Foo", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
fmt.Println("HI", args)
return true
}))
js.Global().Set("Template", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
return Template(args[0].String(), args[1].String())
}))
}
func Template(variable, templateString string) string {
templ := template.New("first")
templ, _ = templ.Parse(templateString)
p := []string{variable}
var result = new(bytes.Buffer)
err := templ.Execute(result, p)
if err != nil {
return ""
}
return result.String()
}
func main() {
c := make(chan struct{}, 0)
println("WASM Go Initialized")
// register functions
registerCallbacks()
<-c
}
@a-x-
Copy link
Author

a-x- commented Jun 3, 2019

GOOS=js GOARCH=wasm go build -o main.wasm
npm add -g serve
serve .
open http://localhost:5000/

@a-x-
Copy link
Author

a-x- commented Jun 3, 2019

Screenshot 2019-06-03 at 22 10 15

@BasilTamm
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment