As Go is becoming the language of the \"system\". I wonder if it\'s possible to run Go code as a script, without compiling it, is there any possibility to do that?
The
Absolutely possible on linux, props to cf: https://blog.cloudflare.com/using-go-as-a-scripting-language-in-linux
In case you don't want to use the already mentioned 'shebang' which may have limitations:
//usr/bin/env go run "$0" "$@"; exit "$?"
Do this instead:
# check if binfmt_misc is already active
# (should already be done through systemd)
mount | grep binfmt_misc
# if not already mounted
sudo mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc
# get gorun and place it so it will work
go get github.com/erning/gorun
sudo mv $GOPATH/bin/gorun /usr/local/bin
# make .go scripts being run with `gorun` wrapper script
echo ':golang:E::go::/usr/local/bin/gorun:OC' | sudo tee /proc/sys/fs/binfmt_misc/register
This is just for one-off testing. To make this persistant, I have this as the second last line in my /etc/rc.local
's:
echo ':golang:E::go::/usr/local/bin/gorun:OC' | tee /proc/sys/fs/binfmt_misc/register 1>/dev/null
If you experience something like 'caching' issues during developing scripts, have a look at /tmp/gorun-$(hostname)-USERID
.
I love bash
, but as soon as you need a proper datastructures (bash arrays and associative arrays don't count due to unusability) you need another language.
Golang is faster to write for me than is python, and any golang setup as depicted above will do for me. No battling python 2 vs 3, its libs and pip horrors, have a distributable binary at will, and just instantly be able to change the source for small one-off scripts is why this approach has definitely its upsides.