简介

GopherJS 可以将 Go 代码编译成纯 JavaScript 代码。其主要目的是为了让你可以使用 Go 来编写前端代码,这些代码可执行在浏览器上运行。你可以通过这里尝试下 GopherJS: GopherJS Playground.

例如 JavaScript 代码:
document.write("Hello world!");

用 GopherJS 来写就变成这样:
js.Global.Get("document").Call("write", "Hello world!")

好像复杂了不少,函数调用这样:

  1. package main
  2. import "github.com/gopherjs/gopherjs/js"
  3. func main() {
  4. js.Global.Set("myLibrary", map[string]interface{}{
  5. "someFunction": someFunction,
  6. })
  7. }
  8. func someFunction() {
  9. //...
  10. }

安装

  1. go get -u github.com/gopherjs/gopherjs
  2. // or
  3. go install github.com/gopherjs/gopherjs@latest

简单Demo

进行pi 运算,结果还真是快

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. "time"
  6. )
  7. func term(k float64) float64 {
  8. return 4 * math.Pow(-1, k) / (2*k + 1)
  9. }
  10. // pi performs n iterations to compute an approximation of pi using math.Pow.
  11. func pi(n int32) float64 {
  12. f := 0.0
  13. for k := int32(0); k <= n; k++ {
  14. f += term(float64(k))
  15. }
  16. return f
  17. }
  18. func main() {
  19. // Start measuring time from now.
  20. started := time.Now()
  21. const n = 50 * 1000 * 1000
  22. fmt.Printf("approximating pi with %v iterations.\n", n)
  23. fmt.Println(pi(n))
  24. fmt.Println("total time taken is:", time.Since(started))
  25. }

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

运行:

  1. $ go run main.go
  2. approximating pi with 50000000 iterations.
  3. 3.1415926735902504
  4. total time taken is: 5.823561654s
  1. $ gopherjs run main.go
  2. gopherjs: Source maps disabled. Install source-map-support module for nice stack traces. See https://github.com/gopherjs/gopherjs#gopherjs-run-gopherjs-test.
  3. approximating pi with 50000000 iterations.
  4. 3.1415926735902504
  5. total time taken is: 2.534s

web 场景应用(主要是一些bindings)

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gopherjs/gopherjs/js"
  5. )
  6. func main() {
  7. fmt.Println("Hello, playground")
  8. js.Global.Call("alert", "Hello, JavaScript")
  9. println("Hello, JS console")
  10. }

编译为JS代码:

  1. gopherjs build app.go

html 页面引用:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <script type="text/javascript" src="./app.js"></script>
  9. </body>
  10. </html>

打开html:
image.png

适用场景

后端golang 编写一次,多次使用,同时性能还不错,目前官方提供了好多方便的binding
比如基于electron 开发的应用使用 gopherjs-electron会有比较大的性能提升,很不错的项目。

References

https://github.com/oskca/gopherjs-electron
https://github.com/gopherjs/gopherjs
https://github.com/rongfengliang/gopherjs-demo