似乎没有完美的解决方案,而且我也不明白为什么不能有一个完美的解决方案。看起来,运行 Go 脚本的方式最为简单,而最没有问题的方法就是使用 go run 命令。[...] 这就是我为什么认为在该语言领域上,仍需要做未完成的工作。同样的,我认为更改程序语言用来忽略 Shebang 不会有任何的危害。
但是,对于 Linux 系统,这里可能会有一个高级技巧,能够在具有完全 Shebang 支持的情况下,从命令行运行 Go 脚本。由 Korchagin 举例子并说明的这种方法,依赖于 Shebang 对 Linux 内核的支持,以及从 Linux 用户空间扩展受到支持二进制格式的可能性。长话短说,Korchagin 建议使用以下方式注册二进制:
$Echo':golang:E::go::/usr/local/bin/gorun:OC'|sudotee/proc/sys/fs/binfmt_misc/register
:golang:E::go::/usr/local/bin/gorun:OC
这样就可以设置完全标准的 Go 语言的可执行位,例如:
packagemain
import(
"fmt"
"os"
)
funcmain(){
s:="world"
iflen(os.Args)>1{
s=os.Args[1]
}
fmt.Printf("Hello,%v!",s)
fmt.Println("")
ifs=="fail"{
os.Exit(30)
}
}
然后执行:
$chmodu xhelloscript.go
$./helloscript.go
Hello,world!
$./helloscript.gogopher
Hello,gopher!
$./helloscript.gofail
Hello,fail!
$Echo$?
30
尽管这种方法无法提供对 REPL 的支持,但是 Shebang 可能足以满足典型的用例。
via: https://www.infoq.com/news/2020/04/go-scripting-language/
作者:Sergio De Simone[19]译者:sunlingbot[20]校对:polaris1119[21]
本文由 GCTT[22] 原创编译,Go 中文网[23] 荣誉推出
参考资料[1]
越来越广泛: https://blog.golang.org/survey2019-results
[2]
正如来自 Codelang 的 Elton Minetto 所说的那样: https://dev.to/codenation/using-golang-as-a-scripting-language-jl2
[3]
Eyal Posener: https://posener.github.io/about/
[4]
更多的理由: https://gist.github.com/posener/73ffd326d88483df6b1cb66e8ed1e0bd
[5]
强调了使用 Go 编写脚本任务的便利程度: https://news.ycombinator.com/item?id=15623106
[6]
帮助 Go 脚本变得更加可靠,并且避免出现像拼写之类的小错误,从而不会出现发生在运行时的报错: https://blog.cloudflare.com/using-go-as-a-scripting-language-in-linux/
[7]
go run: https://golang.org/cmd/go/#hdr-Compile_and_run_Go_program
[8]
github.com/fatih/color: https://github.com/fatih/color
[9]
github.com/schollz/progressbar: https://github.com/schollz/progressbar
[10]
github.com/jimlawless/whereami: https://github.com/jimlawless/whereami
[11]
github.com/spf13/cobra: https://github.com/spf13/cobra
[12]
Neugram: https://github.com/neugram/ng
[13]
由于 Go 语法的所有细节的复杂性: https://news.ycombinator.com/item?id=15623244
[14]
Gomacro: https://github.com/cosmos72/gomacro
[15]
泛型: https://github.com/cosmos72/gomacro#generics
[16]
解释为 Go 的标准详细规范: https://github.com/cosmos72/gomacro/blob/master/doc/code_generation.pdf
[17]
提供 Go 源代码的调试器: https://github.com/cosmos72/gomacro#debugger
[18]
Posener 对使用标准的 Go 语言作为脚本语言的可能性进行了详细分析: https://gist.github.com/posener/73ffd326d88483df6b1cb66e8ed1e0bd
[19]
Sergio De Simone: https://www.infoq.com/profile/Sergio-De-Simone/
[20]
sunlingbot: https://github.com/sunlingbot
[21]
polaris1119: https://github.com/polaris1119
[22]
GCTT: https://github.com/studygolang/GCTT
[23]
Go 中文网: https://studygolang.com/
,