使用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", 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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
2014-04-13 XDomainRequest object
2014-04-13 转 web.config设置之system.webServer 详细介绍,为网站设置默认文档