gopherjs基本用法

  1. 1. hello world
  2. 2. 操作DOM
  3. 3. 输出日志
  4. 4. js调用go

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!")
}

深度截图_选择区域_20210801115723.png

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!")
}

深度截图_选择区域_20210801120404.png

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)
}

深度截图_选择区域_20210801120935.png

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
}

深度截图_选择区域_20210801122443.png


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 wind.kaisa@gmail.com

×

喜欢就点赞,疼爱就打赏