Go实战--gopherjs/gopherjs让你的golang代码在浏览器中执行(Golang转JavaScript)

生命不止,继续 go go go !!!

今天跟大家分享gopherjs.

A compiler from Go to JavaScript for running Go code in a browser

gopherjs介绍及配置

github地址:
https://github.com/gopherjs/gopherjs/

简介:

GopherJS compiles Go code (golang.org) to pure JavaScript code. Its main purpose is to give you the opportunity to write front-end code in Go which will still run in all browsers. Give GopherJS a try on the GopherJS Playground.

文档地址:
https://godoc.org/github.com/gopherjs/gopherjs/js

获取:

go get -u github.com/gopherjs/gopherjs

错误处理:

github.com\gopherjs\gopherjs\compiler\compiler.go:20: undefined: ___GOPHERJS_REQUIRES_GO_VERSION_1_9___
github.com\gopherjs\gopherjs\compiler\package.go:436: o.IsAlias undefined (type *types.TypeName has no field or method IsAlias)

由于之前使用的golang 1.8,而gopherjs是使用golang1.9编译的,所以需要我们也使用golang1.9.这里建议用最新版

安装:

go install -v github.com/gopherjs/gopherjs

判断是否安装成功:

D:\go_workspace\src\go_gopherjs
λ gopherjs
GopherJS is a tool for compiling Go source code to JavaScript.

Usage:
  gopherjs [command]

Available Commands:
  build       compile packages and dependencies
  doc         display documentation for the requested, package, method or symbol
  get         download and install packages and dependencies
  help        Help about any command
  install     compile and install packages and dependencies
  run         compile and run Go program
  serve       compile on-the-fly and serve
  test        test packages
  version     print GopherJS compiler version

Flags:
  -h, --help   help for gopherjs

Use "gopherjs [command] --help" for more information about a command.

如果未成功,就看看golang path bin是否加入了环境变量。

Golang、JavaScript类型对比:

Go typeJavaScript typeConversions back to interface{}
boolBooleanbool
integers and floatsNumberfloat64
stringStringstring
[]int8Int8Array[]int8
[]int16Int16Array[]int16
[]int32, []intInt32Array[]int
[]uint8Uint8Array[]uint8
[]uint16Uint16Array[]uint16
[]uint32, []uintUint32Array[]uint
[]float32Float32Array[]float32
[]float64Float64Array[]float64
all other slicesArray[]interface{}
arrayssee slice typesee slice type
functionsFunctionfunc(…interface{}) *js.Object
time.TimeDatetime.Time
instanceof Node*js.Object
maps, structsinstanceof Objectmap[string]interface{}

gopherjs应用

最简单例子(accessing native javascript apis in go code)
写一个golang文件,姑且命名为main.go:

package main

import "github.com/gopherjs/gopherjs/js"

func main() {
    js.Global.Get("document").Call("write", "Hello world!")
}

运行命令行:

gopherjs build main.go -o demo.js

此时,生成了两个文件demo.js和demo.js.map。

新建一个html文件,姑且命名为test.html,键入:

<!doctype html>
<html>
<head>
  <title>Beginning of Gopherjs</title>
</head>
<body>

<script src="demo.js"></script>
</body>
</html>

打开test.html,查看结果。

操作DOM(honnef.co/go/js/dom)
github地址:
https://github.com/dominikh/go-js-dom

获取:
go get honnef.co/go/js/dom

浏览器播放mp3音频

main.go

package main

import "honnef.co/go/js/dom"

func main() {
    d := dom.GetWindow().Document()

    foo := d.GetElementByID("foo").(*dom.HTMLButtonElement)
    foo.AddEventListener("click", false, func(event dom.Event) {
        a := d.GetElementByID("audio").(*dom.HTMLAudioElement)
        a.Play()
    })
}

`
编译:
gopherjs build main.go -o demo.js

test.html

<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Play Sound on Click Event</title>
</head>
<body>

<button id="foo" type="button">Click Me to Play Sound</button>
<audio id="audio">
  <source src="test.mp3" type="audio/mpeg">
Your browser does not support this audio format.
</audio>

<script src="demo.js"></script>
</body>
</html>

Create and Append Element

main.go

package main

import "honnef.co/go/js/dom"

func main() {
    d := dom.GetWindow().Document()

    foo := d.GetElementByID("foo").(*dom.HTMLDivElement)
    foo.AddEventListener("click", false, func(event dom.Event) {
        div := d.CreateElement("div").(*dom.HTMLDivElement)
        div.Style().SetProperty("color", "red", "")
        div.SetTextContent("I am new div")
        foo.AppendChild(div)
    })
}

编译:
gopherjs build append.go -o demo.js

test.html

<!doctype html>
<html>
<head>
  <title>GopherJS DOM example - Create and Append Element</title>
</head>
<body>

<div id="foo">Click me to create and add new element</div>

<script src="demo.js"></script>
</body>
</html>

更多例子
https://siongui.github.io/2016/01/10/gopherjs-dom-example-getElementById-innerHTML/

    原文作者:大华日记
    原文地址: https://www.jianshu.com/p/931bc47e4809
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞