how to make golang execute a string

时光怂恿深爱的人放手 提交于 2020-11-29 08:54:06

问题


I am not asking to make golang do some sort of "eval" in the current context, just need it to take a input string (say, received from network) and execute it as a separate golang program.

In theory, when you run go run testme.go, it will read the content of testme.go into a string and parse, compile and execute it. Wonder if it is possible to call a go function to execute a string directly. Note that I have a requirement not to write the string into a file.

UPDATE1

I really want to find out if there is a function (in some go package) that serves as an entry point of go, in another word, I can call this function with a string as parameter, it will behave like go run testme.go, where testme.go has the content of that string.


回答1:


AFAIK it cannot be done, and the go compiler has to write intermediate files, so even if you use go run and not go build, files are created for the sake of running the code, they are just cleaned up if necessary. So you can't run a go program without touching the disk, even if you manage to somehow make the compiler take the source not from a file.

For example, running strace on calling go run on a simple hello world program, shows among other things, the following lines:

mkdir("/tmp/go-build167589894", 0700) 
// ....
mkdir("/tmp/go-build167589894/command-line-arguments/_obj/exe/", 0777) 
// ... and at the end of things
unlink("/tmp/go-build167589894/command-line-arguments/_obj/exe/foo") 
// ^^^ my program was called foo.go
// ....
// and eventually:
rmdir("/tmp/go-build167589894")

So you can see that go run does a lot of disk writing behind the scenes, just cleans up afterwards.

I suppose you can mount some tmpfs and build in it if you wish, but otherwise I don't believe it's possible.




回答2:


I know that this question is (5 years) old but I wanted to say that actually, it is possible now, for anyone looking for an up-to-date answer.

The Golang compiler is itself written in Go so can theoretically be embedded in a Go program. This would be quite complicated though.

As a better alternative, there are projects like yaegi which are effectively a Go interpreter which can be embedded into Go programs.



来源:https://stackoverflow.com/questions/28783637/how-to-make-golang-execute-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!