首页 > 其他分享 >Go每日一库之136:gopherjs(将Go代码编译成JS)

Go每日一库之136:gopherjs(将Go代码编译成JS)

时间:2023-09-29 21:12:04浏览次数:34  
标签:github 编译成 JS go Go gopherjs main com

简介

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

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

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

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

package main

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

func main() {
  js.Global.Set("myLibrary", map[string]interface{}{
    "someFunction": someFunction,
  })
}

func someFunction() {
  //...
}

安装

go get -u github.com/gopherjs/gopherjs

// or

go install github.com/gopherjs/gopherjs@latest

简单Demo

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

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。

运行:

$ 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

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

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

编译为JS代码:

gopherjs build app.go

html 页面引用:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript" src="./app.js"></script>
</body>
</html>

打开html:
每日一库之136:gopherjs(将Go代码编译成JS)-0

适用场景

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

References

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

标签:github,编译成,JS,go,Go,gopherjs,main,com
From: https://www.cnblogs.com/arena/p/17737345.html

相关文章

  • Go每日一库之135:Ent(Facebook 开源 Golang 实体框架)
    对于后端开发者来说,一款好用的框架能够大大提升应用的开发效率。为了降低开发者使用TiDB的门槛,方便开发者快速连接到TiDB,我们也在和合作伙伴一起,逐步完善面向主流开发语言和框架的连接支持。近日,Facebook开源的Golang实体框架Ent完成了对TiDB数据库的支持。Ent是......
  • Go每日一库之134:fsm(基有限状态机库)
    开发中,我们经常会遇到这种情况,服务模块有多种状态,它们有一定的顺序,先后执行,逐步切换。这时,fsm这个库可以帮助我们更好的管理多个状态。fsm库,它主要基于两个FSM实现,增加了golang版本的实现:JavascriptFiniteStateMachine,https://github.com/jakesgordon/javascript-state-ma......
  • Go - Using Log Levels
    Examplesofloglevelsfromhightoloware:•Fatal•Error•Warn•Info•DebugTosetuploglevelsforyourlogs,youcanaddtheleveltoeachlineofthelog.ThemoststraightforwardwayofdoingthisistousetheSetPrefixfunction:log.S......
  • JSP功能简介
    JSP能够改变HTML内容getElementById()是多个JavaScriptHTML方法之一。使用该方法来“查找”id="demo"的HTML元素,并把元素内容(innerHTML)更改为"HelloJavaScript":点击前:点击后:JSP能改变HTML的属性通过改变【img】标签的src属性(source)来改变一张HTML图像:点击......
  • CF1425F Flamingoes of Mystery 题解
    题目传送门前置知识前缀和&差分解法令\(sum_k=\sum\limits_{i=1}^{k}a_k\)。考虑分别输入\(sum_2\simsum_n\),故可以由于差分知识得到\(a_i=sum_i-sum_{i-1}(3\lei\len)\),接着输入\(a_2+a_3\)的值从而求出\(a_2=sum_3-a_3,a_1=sum_2-a_2\)。同时因为是交互题,记......
  • Go - Logging to File
    Problem: Youwanttologeventstoalogfileinsteadofstandarderror.Solution: UsetheSetOutputfunctiontosetthelogtowritetoafile. YouuseSetOutputtoredirecttheoutputtoafile.file,err:=os.OpenFile("app.log"......
  • Go - Change What Is Being Logged by the Standard Logger
    Problem: Youwanttochangewhatthestandardloggerlogs.Solution: UsetheSetFlagsfunctiontosetflagsandaddfieldstoeachlogline. Thedefaultbehaviorofthestandardloggeraddsthedateandtimefieldstoeachlineofthelog. Thelogpac......
  • js行内给元素添加或删除类名
    <divclass="none-box2-btn"><divid="boxBtn1"class="none-box2-btn-sonbtnlight"onclick="document.getElementById('boxBtn2').classList.remove('btnlight');document.getEle......
  • Go - logging
    Thelogpackageprovidesseveralfunctionsthatallowyoutowritelogs.Inparticular,therearethreesetsoffunctions:Print•PrintsthelogstotheloggerFatal•Printstotheloggerandcallsos.Exitwithanexitcodeof1Panic•Printstothelo......
  • Go - Inspecting Errors
    Problem: Youwanttocheckforspecificerrorsorspecifictypesoferrors.Solution: Usetheerrors.Isanderrors.Asfunctions.Theerrors.Isfunctioncomparesanerrortoavalueandtheerrors.Asfunctionchecksifanerrorisofaspecifictype. Us......