Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing go code directly into go run without a file

Tags:

go

Is it possible to pass a string of go code into go run instead of go run /some/path/script.go? I tried:

echo "some awesome go code here" | go run

But does not work. Thanks.

like image 551
Justin Avatar asked Oct 26 '13 00:10

Justin


2 Answers

I don't think that there is such an option. At least not with the standard *g compilers or go run.

You can try using gccgo as GCC supports reading from stdin.

like image 157
nemo Avatar answered Sep 30 '22 08:09

nemo


Since I thought that this would be a useful thing to have, I wrote a relatively small Python script that achieves what I think you want. I called it go-script, and here are some usage examples:

# Assuming that test.go is a valid go file including package and imports
$ go-script --no-package < test.go

# Runs code from stdin, importing 'fmt' and wrapping it in a func main(){}
$ echo 'fmt.Println("test")' | go-script --import fmt --main
$ echo 'fmt.Println("test")' | go-script -ifmt -m

Help:

Usage: go-script [options]

Options:
  -h, --help            show this help message and exit
  -i PACKAGE, --import=PACKAGE
                        Import package of given name
  -p, --no-package      Don't specify 'package main' (enabled by default)
  -m, --main            Wrap input in a func main() {} block
  -d, --debug           Print the generated Go code instead of running it.

The source (also available as a gist):

#!/usr/bin/env python

from __future__ import print_function
from optparse import OptionParser
import os
import sys

parser = OptionParser()

parser.add_option("-i", "--import", dest="imports", action="append", default=[],
                  help="Import package of given name", metavar="PACKAGE")

parser.add_option("-p", "--no-package", dest="package", action="store_false", default=True,
                  help="Don't specify 'package main' (enabled by default)")

parser.add_option("-m", "--main", dest="main", action="store_true", default=False,
                  help="Wrap input in a func main() {} block")

parser.add_option("-d", "--debug", dest="debug", action="store_true", default=False,
                  help="Print the generated Go code instead of running it.")

(options, args) = parser.parse_args()

stdin = ""
for line in sys.stdin.readlines():
    stdin += "%s\n" % line

out = ""
if options.package:
    out += "package main\n\n"

for package in options.imports:
    out += "import \"%s\"\n" % package

out += "\n"
if options.main:
    out += "func main() {\n%s\n}\n" % stdin
else:
    out += stdin

if options.debug:
    print(out)
else:
    tmpfile = "%s%s" % (os.environ["TMPDIR"], "script.go")
    f = open(tmpfile, 'w')
    print(out, file=f)
    f.close()
    os.execlp("go", "", "run", tmpfile)
like image 37
fresskoma Avatar answered Sep 30 '22 07:09

fresskoma