Last active
June 3, 2019 20:06
-
-
Save a-x-/c6b8f2b25e3dbd12fbae0a3a64c1fa4a to your computer and use it in GitHub Desktop.
golang wasm. go <-> js interlop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
GOOS=js GOARCH=wasm go build -o main.wasm npm add -g serve serve . open http://localhost:5000/