使用gopherjs 进行web 应用开发

1. 安装

go get -u github.com/gopherjs/gopherjs
2. 基本代码使用
备注: 这个只是一个简单的demo,进行pi 运算,结果还真是快

a. code
golang

package main

import (
	"fmt"
	"math"
	"time"
)

func term(k float64) float64 {
	return 4 * math.Pow(-1, k) / (2*k + 1)
}

// pi performs n iterations to compute an approximation of pi using math.Pow.
func pi(n int32) float64 {
	f := 0.0
	for k := int32(0); k <= n; k++ {
		f += term(float64(k))
	}
	return f
}

func main() {
	// Start measuring time from now.
	started := time.Now()

	const n = 50 * 1000 * 1000
	fmt.Printf("approximating pi with %v iterations.
", n)
	fmt.Println(pi(n))

	fmt.Println("total time taken is:", time.Since(started))
}

一般我们使用go run 运行code
但是使用gopherjs 我们用 gopherjs  run

b. 运行code

go run main.go

approximating pi with 50000000 iterations.
3.1415926735902504
total time taken is: 5.823561654s

gopherjs  run  main.go

gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.
approximating pi with 50000000 iterations.
3.1415926735902504
total time taken is: 2.534s
3. web 开发(主要是一些bindings)
a. 简单的alert code

app.go

package main

import (
	"fmt"

	"github.com/gopherjs/gopherjs/js"
)

func main() {
	fmt.Println("Hello, playground")
	js.Global.Call("alert", "Hello, JavaScript")
	println("Hello, JS console")
}

b.  build  

gopherjs build  app.go

c. html 页面引用

添加  <script>app.js</script>

备注: 没有使用dom 操作的代码使用node 可以直接执行
4. 适用场景
后端golang 编写一次,多次使用,同时性能还不错,目前官方提供了好多方便的binding
比如基于electron 开发的应用使用 gopherjs-electron会有比较大的性能提升,很不错
的项目
5. 参考资料
https://github.com/oskca/gopherjs-electron
https://github.com/gopherjs/gopherjs
https://github.com/rongfengliang/gopherjs-demo
原文地址:https://www.cnblogs.com/rongfengliang/p/8818990.html