Kumar Siva
Kumar Siva

Reputation: 349

How to run function dynamically in 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.

Upvotes: 1

Views: 3293

Answers (2)

captncraig
captncraig

Reputation: 23078

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.

Upvotes: 1

Hannoun Yassir
Hannoun Yassir

Reputation: 21192

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

Upvotes: 4

Related Questions