如何在golang中动态运行功能?

How internally play.golang.org compiles and run the go code?

I have a function as string. I need to check the syntax and run the code inside golang main function.

The code is sent to a server to be compiled and executed then the output is sent back to the client (the browser).

There is an article on how it works : https://blog.golang.org/playground

Go code is a bit hard to run dynamically. You can "check" the syntax with the parser package, although using those packages under go can be a bit tricky. To actually run it, you would likely need to:

  1. Save the function to a temporary directory, possibly generating a main to invoke it.
  2. exec the go compiler to generate an executable
  3. Run the compiled binary, possibly piping stdin and stdout to the parent process.
  4. Communicate with it over stdin/stdout until it exits

This is obviously a big runaround and quite a pain.

If go is not strictly required there are multiple scripting languages with go implementations. If you supply javascript or lua or whatever code, you can run that dynamically.