gopherjs基本用法 - Thu, Jul 29, 2021
gopherjs基本用法
1. hello world
JS
alert('Hello World!')
GO
package main
import "github.com/gopherjs/gopherjs/js"
func main() {
js.Global.Call("alert", "Hello World!")
}
2. 操作DOM
JS
document.write('Hello World!')
GO
package main
import "github.com/gopherjs/gopherjs/js"
func main() {
js.Global.Get("document").Call("write", "Hello world!")
}
3. 输出日志
JS
console.log('Hello World!')
GO
package main
import (
"fmt"
"github.com/gopherjs/gopherjs/js"
)
type User struct {
Name string
Age int
}
func main() {
user := User{
Name: "小明",
Age: 10,
}
js.Global.Get("console").Call("log", "Hello world!")
js.Global.Get("console").Call("log", "user:", user)
println("println user:", user)
fmt.Println("fmt.Println user:", user)
}
4. js调用go
html
<html>
<head>
<script src="gopherjs.js"></script>
</head>
<body>
<div id="output"></div>
<script>
const cmd = {
name: '小明',
age: 10,
};
const result = parse(cmd);
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
go
package main
import (
"encoding/json"
"github.com/gopherjs/gopherjs/js"
)
type User struct {
*js.Object
Name string `js:"name" json:"name"`
Age int `js:"age" json:"age"`
}
func main() {
js.Global.Set("parse", Parse)
}
func Parse(user User) (ret string) {
js.Global.Get("console").Call("log", user)
println("println:", user)
buf, err := json.Marshal(user)
if err != nil {
return
}
ret = string(buf)
println("ret:", ret)
return
}